new Vue({
    el: '#app',
    data() {
        return {
            //流式控制器
            abortCtrl: null,
            streaming: false,
            isflageIOX: true,

            showMTitlePop: false,

            //当前党建会议助手数据id
            meetingId: '',
            voiceDuration: 0,
            meetingName: '',
            //编辑的会议名称
            editMeetingName: '',
            createTime: '',
            createTimeShow: '',
            //实时语音文本
            realtimeVoiceContent: '',

            //i国网录音相关
            voicelist: [],
            timetimer1:null,
            isFlagStartTrue: false,

            clipboard: {
                content: "",
            },
            //步骤
            stepList: [{ id: '1', acIcon: '../images/meetingFour/step1-ac.png', disIcon: '../images/meetingFour/step1-ac.png', step: 1 },
            { id: '2', acIcon: '../images/meetingFour/step2-ac.png', disIcon: '../images/meetingFour/step2-dis.png', step: 3 },
            { id: '3', acIcon: '../images/meetingFour/step3-ac.png', disIcon: '../images/meetingFour/step3-dis.png', step: 4 },
            { id: '4', acIcon: '../images/meetingFour/step4-ac.png', disIcon: '../images/meetingFour/step4-dis.png', step: 6 }
            ],
            //当前步骤:1-实时语音/上传录音2-离线语音3-文档校核页面4-生成内容5-生成方案
            meetingType: 0,
            currentStep: 1,

            //---------------实时语音
            
            // 点击开始是1, 点击暂停是0
            checkClick: 1, 
            time: null,
            one: '00', // 时
            two: '00', // 分    
            three: '00', // 秒
            abc: 0,
            cde: 0, 
            efg: 0,
            //实时语音转写结果查询定时器
            transTimer: null,

            //上传录音文件
            isformClassActive:false,
            isfinish:false,

            //离线语音

            //转写状态
            transStatus: null,
            //预计转写时长
            recordTime: '1分钟',
            transingTip: '排队等待...',
            touchTimer: null,
            offlineVoiceContentEditable: false,
            //发言人编辑
            showSpeakerPop: false,
            updateSpeakerName: '',
            updateSpeakerItem: '',
            updateSpeakerType: 0, //0--语音内容修改发言人,1--校核内容修改发言人
            isEditable: false,
            playProcess: 0,
            //右边播放条
            handleProcessClick: {
                isHandleProcess: false,
                formDom: null,
                scrollTop: 0,
                showBackTopIcon: false
            },
            isDraging: false,
            audioSrc: '',
            isPlaying: false,
            changearr: [],
            nameColor: {},
            colorList: ["#FF88C2", "#FF8888", "#FFA488", "#FFBB66", "#FFDD55", "#FFFF77", "#DDFF77", "#BBFF66", "#66FF66", "#77FFCC", "#77FFEE", "#66FFFF", "	#77DDFF", "#99BBFF", "#9999FF", "#9F88FF", "#B088FF", "#D28EFF", "#E38EFF", "#FF77FF"],
            audio_speaker_content: [],
            playSpeed: 1,
            speedList: [{
                value: 3,
                text: '3x',
            }, {
                value: 2,
                text: '2x',
            }, {
                value: 1.5,
                text: '1.5x',
            }, {
                value: 1,
                text: '1.0x',
            }, {
                value: 0.75,
                text: '0.75x',
            }, {
                value: 0.5,
                text: '0.5x',
            }],

            //------文档校核
            checkContentList: [],
            isCheckEditable: false,
            errorCount: 0,
            //校核类型列表
            defErrorList: [
                {
                    id: 1, 
                    title: '字词错误', 
                    type: 1, 
                    count: 0,
                    data: [
                        // {id: '1', cont: '发言人1:', rightCont:'发言人11:', start: 0, end: 5},
                        // {id: '2', cont: '欺骗', rightCont:'奇葩', start: 145, end:147},
                    ]
                },
                // { 
                //     id: 4, 
                //     title: '专业词语', 
                //     type: 4, 
                //     count: 0,
                //     data: [
                //         // {id: '1', cont: '人类的语音', rightCont:'人类的语言', start: 1, end: 6},
                //         // {id: '2', cont: '慧演', rightCont:'慧眼', start: 12, end: 14}
                //     ]
                // }
            ],
            errorList: [
                {
                    id: 1, 
                    title: '字词错误', 
                    type: 1, 
                    count: 0,
                    data: [
                        // {id: '1', cont: '发言人1:', rightCont:'发言人11:', start: 0, end: 5},
                        // {id: '2', cont: '欺骗', rightCont:'奇葩', start: 145, end:147},
                    ]
                }
            ],
            errContList: [],
            showPositionDialog: false,
            updateError: {},
            //当前错误类型
            errorSel:'',
            errTitle: '错误列表',
            showErrDialog: false,
            showNDialog: false,
            showMDialog: false,

            //生成内容--表单
            //底部生成内容按钮是否显示
            bottomShow: true,
            form: {
                subjectTitle: '',
                contentNeed: '',
                notificationFile: {
                    // "id": "1",
                    // "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf",
                    // "type": "PDF",
                    // "img": "pdf",
                    // "fileSize": 878
                },
                recordFile: {
                    // "id": "1",
                    // "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.doc",
                    // "type": "WORD",
                    // "img": "word",
                    // "fileSize": 878
                },
                highlight:''
            },
            //接口调用sessionId
            infSessionId: '',
            improveFile: {},
            //选中续写等功能
            curPId: '',
            quickSel: '',
            quickList: [{ id: '1', title: '扩写', type: 'expand' }, { id: '2', title: '续写', type: 'continued' }, { id: '3', title: '润色', type: 'polish' }],
            //扩写、续写、润色生成的待替换内容
            replaceContent: '',
            //扩写、续写、润色生成md转html
            replaceHtmlContent:'',
            //方案内容
            programMdContent: '',
            programHtmlContent: '',
            requireText: '',
            //显示续写扩写弹出框
            showExConPo: false,
            //续写扩写润色标题
            writeTitle:'',
            generating: true,

            //编辑
            showEditDialog: false,
            //编辑生成内容
            editGenCont: '',
            //编辑中的内容
            tempEditGenCont: '',
            actions:[{ text: '编辑' }],
            //需要添加监听事件的元素
            addElementList: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li'],

            //会议记录文档
            offlineWord: {},
            //生成摘要文档
            wordResult: {},
            //录音文件
            voiceAttach: {},
            //ppt格式方案
            pptResult: {},
            //ppt结果显示
            pptLoading: false,

            //上传文件
            //-1:无文件，0-会议通知上传，1-扩写等上传，2-会议记录
            fileType: -1,
            improveFile: {},
            //进度条
            progress: 0,
            progressBar: false,
            disabledInp: false,
            fileName: '',
            // 设置每个分片的大小（字节）
            CHUNK_SIZE: 5 * 1024 * 1024 + "", // 1MB
            retryNum: 0,
            myindex: -1,
            fileSuffixs: ["doc", "docx"],
            pdfAndImgSuffixs: ["pdf", "jpg", "jpeg", "png", "bmp"],
            pdfSuffix: ['pdf'],
            imgSuffix: ["jpg", "jpeg", "png", "bmp"],
            voiceSuffixs: ['mp3', 'wav', 'pcm', 'amr', 'm4a',"MP3","WAV","PCM","AMR","M4A"],
            showErrList: false,

            //语音
            voiceType: 0, //0:没有录音,1:实时语音
            subjectTalking: false,
            voiceContentTmp: [],
            MODEL_CODE: '1888', 
            CAPACITY_CODE: '010115',
            LANG: 'zh',
            WS_URL: '',
            checkSwitch: false,
            wsChannelId: generateUUID(),
            VoiceItemID: generateUUID(),
            count: 0,
            bufferData: [],
            voiceTxt:{
                ind: '',
                old: ''
            },
            myWebsocket: null,

        }
    },
    watch: {
    },
    filters: {
        recordTimeText: (value) => {
            if (!value) return '1分钟';
            const h = Math.floor(value / 3600)
            const m = Math.floor(value % 3600 / 60)
            const s = Math.floor(value % 60)
            if (h) {
                return `${h}小时${m}分钟`
            }
            if (m) {
                return `${m}分钟`
            }
            return `1分钟`
        },
    },
    beforeDestroy() {
        console.log("----------beforeDestroy")
        this.stopRecorder()
    },
    created() {
        const _this = this
        let jsApiList = []
        let current_meeting_step = sessionStorage.getItem('current_meeting_step')
        this.currentStep = current_meeting_step ? current_meeting_step : this.currentStep
        let _meetingType = sessionStorage.getItem('meeting_type')
        this.meetingType = null != _meetingType ? _meetingType : 1
        this.meetingId = sessionStorage.getItem('meeting_id')

        sessionStorage.removeItem('current_meeting_step')
        sessionStorage.removeItem('meeting_type')
        sessionStorage.removeItem('meeting_id')
        $.getScript("../../../js/jweixin-sgccigw-1.0.0.js" /*"js/jweixin-1.0.0.js"*/, () => {
            'use strict';
            wx.ready(() => {
                wx.onHistoryBack(() => {
                    _this.home()
                    return false
                })

                // if(this.meetingId) {
                //     this.stopRecorder()
                // }
                if(0 == this.meetingType && !this.meetingId) {
                    this.startTalk(1)
                }
            });
            jsApiList = [
                'startRecord',
                'stopRecord',
                'onVoiceRecordEnd',
                'translateVoice',                
                'previewFile',
                'startRecordVoiceBuffer',
                'ext_AudioRecorder_Start',
                'ext_AudioRecorder_Stop',
                'onRecordBufferReceived',
                'multiWindows_subscribe',
                'stopRecord',
                'onHistoryBack',
            ];
            wx.config({
                beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: corpid,
                timestamp: '1626832073',
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: jsApiList
            });
        });
    },
    mounted() {
        this.compatibleInput()

        this.addPopoverClick()

        window.addEventListener('resize', this.handleResize())

        if(this.meetingId) {
            this.checkClick = 0
            this.$nextTick(() => {
                setTimeout(() => {
                    this.queryById(this.meetingId)
                }, 200);
            })
        }else {
            this.createMeeting()
        }

        // this.isformClassActive = true
        // this.showPositionDialog = true
        // this.updateError = {
        //     "cont": "aaa",
        //     "rightCont": "bbbb"
        // }

        // this.fileName = "wawfwefwef.mp3"
        // this.channelId = ""
        // this.isformClassActive = false
        // this.progressBar = false
        // this.progress = 0
        // this.fileName = ''
        // this.startOfflineTrans()

        // this.setCheckContentList()
        // this.setSpeakerNameColor(this.checkContentList)

        // this.errorList = this.defErrorList

        // this.meetingId = '2524a6ad516c4d468c4b968d57f8ef66'
        // this.currentStep = 2
        // this.queryTransResult('2524a6ad516c4d468c4b968d57f8ef66')
        // this.audioSrc = './111.mp3'
        
        // this.currentStep = 3
        // this.queryTransResult('c275a37825284fa3bc238f95caeb5c4f')
        // this.setCheckContentList()
        // this.setSpeakerNameColor(this.checkContentList)

        // this.currentStep = 4
        // this.form.subjectTitle = this.meetingName
        // this.form.recordFile = {
        //     "id": "4134",
        //     "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.doc",
        //     "type": "WORD",
        //     "img": "word",
        //     "fileSize": 4134
        // }
        // this.form.notificationFile = {
        //     "id": "1",
        //     "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf",
        //     "type": "PDF",
        //     "img": "pdf",
        //     "fileSize": 878
        // }

        // this.currentStep = 6
        // this.wordResult = {
        //     id: '1', fileName: '人工智能：塑造未来的技术力量11.docx', type: 'word', fileSize: '126.35KB' 
        // }
        // this.offlineWord = {
        //     id: '1', fileName: '会议记录.docx', type: 'word', fileSize: '126.35KB' 
        // }
        // this.pptLoading = true
        // this.pptResult = {
        //     id: '1', fileName: '人工智能：塑造未来的技术力量.pdf', type: 'pdf', fileSize: '126.35KB' 
        // }

        // this.voiceDuration = 10000
        // this.startRealtimeTrans()

        // this.testChat()
    },
    methods: {
        testChat() {
            
            // 生成内容后台请求
            const userId = sessionStorage.getItem("userId");
            
            let param = {
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            
            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/common/chat", param,
                (res) => {
                    //成功回调
                    console.log(res)
                }, (err) => {
                    //失败回调
                }, res => {
                });
        },
        test4() {
            this.currentStep = 5

            // this.genContent()
            this.programMdContent = 
            `# 关于2024.12.27党建工作会议会议纪要\n\n2024年12月27日，召开了一场关于党建工作的会议，发言人1、发言人2、发言人3参加会议。会议分别听取了关于天津首次为大型活动开展绿电交易的情况，以及能源清洁低碳转型、京津冀协同发展等议题的讨论，发言人1作会议总结。有关情况纪要如下：\n\n**会议认为，** 天津首次为夏季达沃斯论坛进行的绿电交易，不仅实现了活动期间百分百绿电供应，还标志着在大型活动绿色能源利用方面的新突破。此次交易不仅节约了大量标煤，减少了二氧化碳排放，同时也为后续大型活动的绿色筹办提供了新思路。此外，能源清洁低碳转型是国家能源安全和碳达峰、碳中和目标实现的关键，天津在这一领域的探索和实践具有重要的示范意义。\n\n**会议要求，** 加快推进绿电交易和清洁能源的利用，促进能源结构的优化升级。\n\n**一是加强绿电交易的推广，** 必须加快绿电绿证交易的规模，引导社会形成绿色电力消费意识，推动能源清洁低碳转型。请相关部门研究制定更多激励政策，鼓励企业和个人参与绿电交易，同时加强与新能源企业的合作，确保绿电供应稳定可靠。\n\n**二是推动能源转型和科技创新，** 要充分利用天津在能源转型、节能增效、低碳服务等方面的优势，加强技术研发和创新实践，如“雪豹网”、“零能耗小屋”等项目的推广，提升能源使用效率和环保水平。\n\n**三是深化京津冀协同发展，** 要继续打破区域壁垒，优化产业结构，促进交通、产业、民生、科技创新等领域的深度融合，提升区域整体竞争力和可持续发展能力。\n\n**四是强化公共服务共建共享，** 要加强京津冀三地在教育、医疗等领域的合作，提升公共服务质量和效率，让市民享受更多的实惠和便利。\n\n**会议强调，** 在推进能源清洁低碳转型的过程中，要特别注重科技创新和政策引导，发挥天津在京津冀协同发展中的重要作用，同时深化公共服务领域的共建共享，确保人民群众在绿色发展中受益。\n\n主持：XXX\n\n参会人员：发言人1、发言人2、发言人3\n\n记录：XXX`,
            this.programHtmlContent = this.markdown2Html(this.programMdContent)
            this.handleScrollBottom('contentRef')
            this.addClickEvent()
            this.addPopoverClick()
        },
        createMeeting() {
            this.createTime = new Date()
            this.createTimeShow = dateFormat('yyyy-MM-dd hh:mm', this.createTime)
            this.meetingName = dateFormat('yyyyMd', this.createTime) + '_党建会议记录'

            // if(0 == this.meetingType) {
            //     this.createRealMeeting()
            // }
        },
        getVoiceDuration() {
            let minute = Math.floor(this.voiceDuration/60) + ''
            let second = this.voiceDuration%60 + ''
            if(minute.length == 1) {
                minute = '0' + minute
            }
            if(second.length == 1) {
                second = '0' + second
            }
            return minute+":"+second
        },
        getCreateTimeDate() {
            return dateFormat('yyyy年MM月dd日', this.createTime)
        },
        getCreateTimeHour() {
            return dateFormat('hh:mm', this.createTime)
        },
        editTitle() {
            if(-1 == this.transStatus || 0 == this.transStatus) {
                mui.toast('语音转写中不能修改', {
                    duration: 'long',
                    type: 'div'
                })
                return
            }
            this.showMTitlePop = true
            this.editMeetingName = this.meetingName
        },
        cancelTitleEdit() {
            this.showMTitlePop = false
        },
        handleMeetitleEdit() {
            if('' == this.editMeetingName) {
                mui.toast('会议名称不能为空', {
                    duration: 'long',
                    type: 'div'
                })
                return
            }
            this.updateMeeting({
                'updateType': 0,
                'meetingName': this.editMeetingName
            })
        },
        handleTouchStart(event, item) {
            this.touchTimer = setTimeout(() => {
                this.offlineVoiceContentEditable = true
                this.isEditable = true
            }, 1000);
        },
        handleTouchEnd(item) {
            this.touchTimer = clearTimeout(this.touchTimer)
            console.log("长按结束")
        },
        handleSpeakerEdit(item, type) {
            if(1 == type && !item.showSpeakerName) {
                return
            }
            this.updateSpeakerName = item.speakerName;
            this.updateSpeakerItem = {...item};
            this.updateSpeakerType = type
            this.showSpeakerPop = true;
        },
        cancelSpeakerEdit() {
            this.showSpeakerPop = false
            this.updateSpeakerName = ""
        },
        editSpeakerCurrent() {
            if(0 == this.updateSpeakerType) {
                if (this.updateSpeakerName !== this.updateSpeakerItem.speakerName) {
                    this.audio_speaker_content.forEach(
                        speaker => {
                            if (speaker.paragraphId == this.updateSpeakerItem.paragraphId && 
                                speaker.speakerId == this.updateSpeakerItem.speakerId) {
                                speaker.speakerName = this.updateSpeakerName ? this.updateSpeakerName : "发言人"
                            }
                        }
                    );
                    this.updateSpeakerName = "";
                }
                this.showSpeakerPop = false;

                this.updateMeeting({
                    'updateType': 3,
                    "offlineVoiceContent": this.audio_speaker_content
                })
            }else {
                if (this.updateSpeakerName !== this.updateSpeakerItem.speakerName) {
                    this.checkContentList.forEach(
                        speaker => {
                            if (speaker.id == this.updateSpeakerItem.id) {
                                speaker.speakerName = this.updateSpeakerName ? this.updateSpeakerName : "发言人"
                            }
                        }
                    );
                    this.updateSpeakerName = "";
                }
                this.showSpeakerPop = false;

                this.updateMeeting({
                    'updateType': 3,
                    "checkContent": this.checkContentList
                })
            }
        },
        editSpeakerConfirm() {
            if(0 == this.updateSpeakerType) {
                if (this.updateSpeakerName !== this.updateSpeakerItem.speakerName) {
                    this.audio_speaker_content.forEach(
                        speaker => {
                            if (speaker.speakerId == this.updateSpeakerItem.speakerId 
                                && speaker.speakerName == this.updateSpeakerItem.speakerName) {
                                speaker.speakerName = this.updateSpeakerName ? this.updateSpeakerName : "发言人"
                            }
                        }
                    );
                    this.updateSpeakerName = "";
                }
                this.showSpeakerPop = false;
    
                this.updateMeeting({
                    'updateType': 3,
                    "offlineVoiceContent": this.audio_speaker_content
                })
            }else {
                if (this.updateSpeakerName !== this.updateSpeakerItem.speakerName) {
                    this.checkContentList.forEach(
                        speaker => {
                            if (speaker.speakerId == this.updateSpeakerItem.speakerId) {
                                speaker.speakerName = this.updateSpeakerName ? this.updateSpeakerName : "发言人"
                            }
                        }
                    );
                    this.updateSpeakerName = "";
                }
                this.showSpeakerPop = false;

                this.updateMeeting({
                    'updateType': 3,
                    "checkContent": this.checkContentList
                })
            }
        },
        handleOfflineEdit() {
            this.isEditable = true
            mui.toast('点击文本进行编辑', {
                duration: 'long',
                type: 'div'
            })
        },
        handleOfflineCopy() {
            let copyContent = []
            this.audio_speaker_content.forEach((item, itemIndex) => {
                let tmp_item_content = new Array()
                let copyItem = {...item}
                copyContent.push(copyItem)
                copyItem.content.forEach(content => {
                    let current_divs = document.querySelectorAll('[data-id="'+content.serialNum+'"]');
                    current_divs.forEach((current_div, index) => {
                        let text = current_div.innerText

                        let _content = JSON.parse(JSON.stringify(content))
                        if(0 < index) {
                            _content.serialNum = generateUUID()
                        }
                        _content.word = text
                        tmp_item_content.push(_content)
                    })
                    
                })
                this.$set(copyItem, 'content', tmp_item_content)
            })

            var datas = JSON.parse(JSON.stringify(copyContent))
            var text = ''
            datas.forEach((item, index1) => {
                if (index1 == 0) {
                    text += item.speakerName + "\n"
                } else {
                    text += "\n" + item.speakerName + "\n"
                }
                item.content.forEach((content, index2) => {
                    // if (i.subIndex == -1) {
                    //     i.word = "\n" + i.word
                    // }
                    text += content.word

                    if(index2 < item.content.length-1) {
                        text += "\n"
                    }
                })
            })

            this.mycopy(text, 'offline-copy')
        },
        mycopy(content, className) {
            if (content == '' || content.split(" ").join("").length == 0) {
              mui.toast('内容不能为空', {
                duration: 'long',
                type: 'div'
              })
              return
            }

            this.$nextTick(() => {
                var clipboard = new Clipboard('.'+className, {
                    // 通过target指定要复印的节点
                    text: function () {
                        return content
                    }
                });
                clipboard.on('success', (e) => {
                    mui.toast('复制成功', {
                        duration: 'long',
                        type: 'div'
                    })
                });
                clipboard.on('error', (e) => {
                    mui.toast('复制失败', {
                        duration: 'long',
                        type: 'div'
                    })
                });
            })
        },
        clickFunc(val) {
            console.log('val', val)
            if (val === 'play') {
                this.isPlaying = !this.isPlaying
                console.log(this.$refs.audio)
                this.$refs.audio.play()
            } else if (val === 'pause') {
                this.isPlaying = !this.isPlaying
                this.$refs.audio.pause()
            } else if (val === 'speed') {
                console.log(this.playSpeed);
                this.$refs.audio.playbackRate = this.playSpeed
            } else if (val === 'forward') {
                // 减慢音频播放速度，速率范围[0.5，2]
                if (this.playSpeed < 2) {
                    this.playSpeed += 0.5
                    this.$refs.audio.playbackRate = this.playSpeed
                }
            } else if (val === 'refresh') {
                this.$refs.audio.playbackRate = 1
                this.playSpeed = 1
                this.$refs.audio.load()
                this.$refs.audio.play()
            }
        },
        playPause() {
            console.log('playPause', this.isPlaying)
            if (!this.isPlaying) {
                clearInterval(this.cursorTimer);
                this.$refs.audio.pause();
            } else {
                this.cursorTimer = setInterval(this.updateCursor, 100);
                this.$refs.audio.play();
            }
        },
        updateCursor() {
            var audioDuration = this.$refs.audio.duration; // 获取音频总时长
            var currentTime = this.$refs.audio.currentTime; // 获取当前播放时间
            this.changearr.forEach((item) => {
                if (Number(item.startTime) / 1000 <= currentTime && currentTime <= Number(item.endTime) / 1000) {
                    // console.log(document.getElementById(item.serialNum))
                   if(document.getElementById(item.serialNum)) {
                       document.getElementById(item.serialNum).style.background = 'rgb(175, 226, 252)';
                   }
                    //当前音频距离顶部的距离
                    this.handleProcessClick.scrollTop = document.getElementById(item.serialNum).offsetTop
                    // console.log('this.handleProcessClick.scrollTop', this.handleProcessClick.scrollTop)

                    //判断是否为拖动滚动条
                    // console.log('updateCursor----', this.handleProcessClick.isHandleProcess)
                    if (!this.handleProcessClick.isHandleProcess) {
                        document.getElementById(item.serialNum).scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });
                    }
                } else {
                    if(document.getElementById(item.serialNum)) {
                        document.getElementById(item.serialNum).style.background = 'none';
                    }
                }
            })
        },
        setProcessFunc(val) {
            this.$refs.audio.currentTime = Math.round((val / 100) * this.totalTimes)
            this.$refs.audio.play()
            // 重置拖动 setTimeout等滚动条滚到相应位置后再改变isHandleProcess状态
            setTimeout(() => {
                this.handleProcessClick.isHandleProcess = false
            }, 2000)
        },
        readText(item) {
            this.$refs.audio.currentTime = Number(item.startTime) / 1000
            setTimeout(() => {
                this.handleProcessClick.isHandleProcess = false
            }, 1000)
            console.log(item)
        },
        getSpeakerNameColor(item) {
            return "color: " + this.nameColor[item] + ";";
        },
        setSpeakerNameColor(list) {
            this.nameColor = []
            list.forEach((item) => {
                if (!this.nameColor[item.speakerName]) {
                    this.nameColor[item.speakerName] = this.colorList[Object.keys(this.nameColor).length];
                }
                if (item.content) {
                    item.content.forEach((i) => {
                        if (i.subIndex == -1) {
                            i.word = i.word + "\n"
                        }
                        this.changearr.push(i)
                    })
                }
            })
        },
        // 开始
        playFunc() {
            console.log('playFunc', this.isPlaying)
            this.playPause();
            this.isPlaying = true
            this.$emit('play', this.isPlaying)
        },
        // 暂时
        pauseFunc(e) {
            // console.log('music is paused')
            this.isPlaying = false
            this.$emit('pause', this.isPlaying)
            clearInterval(this.cursorTimer);
        },
        waitingFunc(e) {
            this.isLoading = true;
        },
        timeupdateFunc(e) {
            if (!this.isDraging) {
                this.playProcess = (e.target.currentTime / this.totalTimes) * 100
                this.currentTime = e.target.currentTime
            }
            this.$emit('timeupdate', this.currentTime, this.playProcess)
            this.isLoading = false;
        },
        async canplayFunc(e) {
            const firsthandAudio = e.target;
            while (firsthandAudio.duration === Infinity) {
                await new Promise(r => setTimeout(r, 200));
                firsthandAudio.currentTime = 10000000 * Math.random();
            }
            this.totalTimes = firsthandAudio.duration;
            this.isError = false
            this.$refs.audio.volume = 0.5
        },
        errorFunc(e) {
            this.isError = true
        },
        preStep() {
            if(this.streaming) {
                mui.toast('生成中不能跳转', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            if(this.abortCtrl) {
                this.stopGen()
            }
            this.currentStep -= 1

            if(2 == this.currentStep) {
                this.setSpeakerNameColor(this.audio_speaker_content)
            }
        },
        nextStep() {
            if(this.streaming) {
                mui.toast('生成中不能跳转', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            if(this.abortCtrl) {
                this.stopGen()
            }
            this.showErrDialog = false
            if(1 == this.currentStep) {
                this.currentStep += 1
                if(this.meetingType == 0) {
                    //跳转到实时语音
                    this.stopTalk(1)
                    this.startRealtimeTrans()
                }else if(this.meetingType == 1){
                    this.startOfflineTrans()
                }
                this.loadOffline()
                // $(".curtain").css("display", "block");
            }else if(2 == this.currentStep) {
                if(this.transingTip == "转写失败") {
                    mui.toast("转写失败，请重试", { duration: "long", type: "div" });
                    return
                }
                if(!this.meetingId || this.transStatus != 1) {
                    mui.toast("请等待语音识别", { duration: "long", type: "div" });
                    return
                }
                this.clickFunc('pause')
                //离线语音进入文档校核
                //更新编辑内容
                this.updateSpeakerContent()
                var i = 0;
                mui.confirm("文档校核需要较长时间，是否跳过该步骤进入下一步", "文档校核", ["校核", "跳过"], (e) => {
                    if (i > 0) return;
                    i++;
                    if (e.index == 1) {
                        $(".curtain").css("display", "block");
                        //跳过校核,更新校核状态为1
                        this.updateMeeting({
                            "updateType": 4,
                            "checkStatus": 1
                        })
                        this.currentStep += 1
                        this.setCheckContentList()
                        this.nextStep()
                    } else {
                        this.currentStep += 1
                        // $(".curtain").css("display", "block");
                        //文档校核
                        this.errorList = this.defErrorList
                        setTimeout(() => {
                            this.contentCheck()
                        }, 100);
                    }
                });
            }else if(3 == this.currentStep) {
                //当前为文档校核，进入生成内容表单填写页面
                $(".curtain").css("display", "block");
                this.currentStep += 1
                this.showErrDialog = false
                //生成离线语音文档
                this.createOfflineDoc()
            }else if(4 == this.currentStep) {
                //当前为会议助手表单页面，进入扩写页面
                //表单校验
                if(!this.form.subjectTitle) {
                    mui.toast("请填写主题", { duration: "long", type: "div" });
                    return
                }
                if(!this.form.recordFile.id) {
                    mui.toast("请上传会议记录", { duration: "long", type: "div" });
                    return
                }
                $(".curtain").css("display", "block");
                this.currentStep += 1
                this.programMdContent = ''
                this.programHtmlContent = ''
                this.stopTalk()
                //生成内容
                this.genContent()
            }else if(5 == this.currentStep) {
                let myPopover = document.getElementById('myPopover')
                myPopover.style.display = 'flex'

                //创建文档
                this.currentStep += 1
                this.createDoc()
            }
        },
        /**
         * 更新编辑语音内容
         */
        updateSpeakerContent() {
            this.audio_speaker_content.forEach((item, itemIndex) => {
                let tmp_item_content = new Array()
                item.content.forEach(content => {
                    let current_divs = document.querySelectorAll('[data-id="'+content.serialNum+'"]');
                    current_divs.forEach((current_div, index) => {
                        let text = current_div.innerText

                        let _content = JSON.parse(JSON.stringify(content))
                        if(0 < index) {
                            _content.serialNum = generateUUID()
                        }
                        _content.word = text
                        tmp_item_content.push(_content)
                    })
                    
                })
                this.$set(item, 'content', tmp_item_content)
                this.$set(this.audio_speaker_content, itemIndex, item)
            })

            // this.audio_speaker_content.forEach(item => {
            //     item.content.forEach(content => {
            //         content.word = document.getElementById(content.serialNum).innerText
            //     })
            // })
        },
        /**
         * 更新会议记录
         * updateType:0-标题 1-实时语音内容 2-校核更正结果 3-修改发言人 4-修改校核状态
         */
        updateMeeting(param) {
            let errMsg = "标题修改失败"
            if(1 == param.updateType) {
                errMsg = '实时语音内容更新失败'
            }else if(2 == param.updateType) {
                errMsg = '校核更正失败'
            }else if(3 == param.updateType) {
                errMsg = '发言人修改失败'
            }else if(4 == param.updateType) {
                errMsg = '校核失败'
            }

            const userId = sessionStorage.getItem("userId");
            param['userId'] = userId
            param['id'] = this.meetingId
            param['timestamp'] = new Date().getTime() + ""
            let AuthenticationSession = sessionStorage.getItem("Authentication");

            // console.log("meeting更新参数", param)
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/updateMeeting",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        console.log(res.resultValue)
                        if(0 == param.updateType) {
                            this.meetingName = param.meetingName
                            this.showMTitlePop = false
                        }
                    }else {
                        //失败
                        $(".curtain").css("display", "none");
                        if(1 != param.updateType && 4 != param.updateType) {
                            mui.toast(errMsg, { duration: "long", type: "div" });
                        }
                    }
                },
                error: (e) => {
                    //失败
                    $(".curtain").css("display", "none");
                    if(1 != param.updateType && 4 != param.updateType) {
                        mui.toast(errMsg, { duration: "long", type: "div" });
                    }
                },
            });
        },
        /**
         * 创建实时语音党建会议初始化数据
         */
        createRealMeeting() {
            //实时录音，创建初始化会议记录
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "meetingName": this.meetingName,
                "createTime": dateFormat('yyyy-MM-dd hh:mm:ss', this.createTime),
                "meetingType": 0,
                "realtimeSessionId": this.VoiceItemID,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/createMeeting",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        console.log(res.resultValue)
                        this.meetingId = res.resultValue.id
                    }else {
                    //失败
                    $(".curtain").css("display", "none");
                    mui.toast("创建党建会议记录失败", { duration: "long", type: "div" });
                    }
                },
                error: (e) => {
                    //失败
                    $(".curtain").css("display", "none");
                    mui.toast("创建党建会议记录失败", { duration: "long", type: "div" });
                },
            });
        },
        startRealtimeTrans() {
            userId = sessionStorage.getItem("userId");
            if (sessionStorage.getItem("iscp_port")) {
              iscp_port = sessionStorage.getItem("iscp_port");
            } else {
              iscp_port = ""
            }
            let param = {
              "userId": userId,
              "id": this.meetingId,
              "meetingName": this.meetingName,
              "createTime": dateFormat('yyyy-MM-dd hh:mm:ss', this.createTime),
              "meetingType": 0,
              "realtimeVoiceContent": this.realtimeVoiceContent,
              "realtimeSessionId": this.VoiceItemID,
              "timestamp": new Date().getTime() + "",
            };
            console.log("上传参数");
            console.log(param);
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                  url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/startRealtimeTrans",
                  type: "post",
                  async: false, //是否同步，false表示同步请求
                  dataType: "json",
                  data: data,
                  headers: {
                      "Content-Type": "application/json;charset=UTF-8",
                      Authentication: AuthenticationSession,
                      sign: sign
                  },
                  success: (res, txt, xhr) => {
                      if (res.code == 200) {
                          console.log(res.resultValue);

                          this.transTimer = setInterval(() => {
                            this.queryTransResult(res.resultValue.id)
                          }, 5000);
                      }else {
                        this.transErrCallBack()
                      }
                  },
                  error: (e) => {
                      //失败回调
                      this.fileloading = false
                      this.uploadFile = {}
                      this.downFileType = ''
                      this.transErrCallBack()
                      $(".curtain").css("display", "none");
                    //   mui.toast("转写失败", { duration: "long", type: "div" });
                  },
              });
        },
        startOfflineTrans() {
            userId = sessionStorage.getItem("userId");
            if (sessionStorage.getItem("iscp_port")) {
              iscp_port = sessionStorage.getItem("iscp_port");
            } else {
              iscp_port = ""
            }
            this.meetingName = this.fileName.substr(0, this.fileName.lastIndexOf(".")) || this.meetingName
            let param = {
              "id": this.meetingId,
              "userId": userId,
              "meetingName": this.meetingName,
              "createTime": dateFormat('yyyy-MM-dd hh:mm:ss', this.createTime),
              "meetingType": 1,
              "voiceAttach": this.channelId,
              "timestamp": new Date().getTime() + "",
            };
            console.log("上传参数");
            console.log(param);
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                  url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/startOfflineTrans",
                  type: "post",
                  async: false, //是否同步，false表示同步请求
                  dataType: "json",
                  data: data,
                  headers: {
                      "Content-Type": "application/json;charset=UTF-8",
                      Authentication: AuthenticationSession,
                      sign: sign
                  },
                  success: (res, txt, xhr) => {
                      if (res.code == 200) {
                          console.log(res.resultValue);
                          this.meetingId = res.resultValue.id
                          this.transTimer = setInterval(() => {
                            this.queryTransResult(res.resultValue.id)
                          }, 5000);
                      }else {
                        this.transErrCallBack()
                      }
                  },
                  error: (e) => {
                      //失败回调
                      this.fileloading = false
                      this.uploadFile = {}
                      this.downFileType = ''
                      $(".curtain").css("display", "none");
                      this.transErrCallBack()
                    //   mui.toast("转写失败", { duration: "long", type: "div" });
                  },
              });
        },
        transErrCallBack() {
            setTimeout(() => {
                // //转写失败...
                // this.channelId = ""
                // this.isformClassActive = false
                // this.progressBar = false
                // this.progress = 0
                // this.fileName = ''
                // this.fileloading = false
                // this.uploadFile = {}
                // this.downFileType = ''
                this.transingTip = "转写失败"
                $(".curtain").css("display", "none");
                if(this.transTimer) {
                    // mui.toast("转写失败", { duration: "long", type: "div" });
                    clearInterval(this.transTimer)
                }
                // this.transingTip = ''
                // this.currentStep = 1

                mui.confirm(
                    "转写失败，请重试",
                    "",
                    ["取消", "确定"],
                    (e) => {
                        if (e.index == 1) {
                            console.log("重新转写")
                            this.transingTip = ''
                            if(0 == this.meetingType) {
                                this.startRealtimeTrans()
                            }else {
                                this.startOfflineTrans()
                            }
                        } else {
                            console.log("取消重试")
                        }
                    }
                );
            }, 500);
        },
        queryById(id) {
            const userId = sessionStorage.getItem("userId");
            let param = {
              "id": id,
              "timestamp": new Date().getTime() + ""
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/queryById",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                  if (res.code == 200) {
                    this.transStatus = res.resultValue.transStatus
                    this.meetingId = res.resultValue.id
                    this.meetingName = res.resultValue.meetingName
                    this.voiceDuration = Number(res.resultValue.voiceDuration)
                    this.createTime = res.resultValue.createTime

                    if(this.transStatus != 1) {
                        if(0 == res.resultValue.meetingType) {
                            //实时语音
                            //第一步
                            this.currentStep = 1
                            this.checkClick = 0
                            this.createTimeShow = dateFormat('yyyy-MM-dd hh:mm', res.resultValue.createTime)
                            this.realtimeVoiceContent = res.resultValue.realtimeVoiceContent
                            this.VoiceItemID = res.resultValue.realtimeSessionId

                            let hour = Math.floor(this.voiceDuration/3600) + ''
                            let t_voice_duration = this.voiceDuration%3600
                            let minute = Math.floor(t_voice_duration/60) + ''
                            let second = t_voice_duration%60 + ''
                            if(hour.length == 1) {
                                hour = '0' + hour
                            }
                            if(minute.length == 1) {
                                minute = '0' + minute
                            }
                            if(second.length == 1) {
                                second = '0' + second
                            }
                            this.one = hour
                            this.two = minute
                            this.three = second

                            this.stopRecorder()

                        }else if(1 == res.resultValue.meetingType){
                            //上传录音文件
                            this.currentStep = 2
                            this.createTimeShow = dateFormat('yyyy-MM-dd hh:mm', res.resultValue.createTime)
                            this.channelId = res.resultValue.voiceAttach
                            this.startOfflineTrans()
                        }
                    }else if(this.transStatus == 1 && 1 != res.resultValue.checkStatus) {
                      //第二步，
                      this.currentStep = 2
                      console.log(res.resultValue)
                      this.voiceDuration = Number(res.resultValue.voiceDuration)
                      this.audio_speaker_content = JSON.parse(res.resultValue.offlineVoiceContent)
                      
                      let downUrl = localUrlLink + iscp_port + '/tjAiAssistant/common/download';
                      downUrl += '?id=' + res.resultValue.voiceAttach + '&userId=' + userId;
                      let Authentication = sessionStorage.getItem("Authentication");
                      let timestamp = new Date().getTime()+"";
                      let sign = sm3(timestamp + '&' + res.resultValue.voiceAttach)
                      downUrl += '&Authentication=' + Authentication + '&timestamp=' + timestamp + '&sign=' + sign;
                      console.log('预览地址', downUrl)
                      this.audioSrc = downUrl
                      
                      this.setSpeakerNameColor(this.audio_speaker_content)
                      if(this.transTimer) {
                        clearInterval(this.transTimer)
                      }
                    }else if(1 == res.resultValue.checkStatus && !res.resultValue.offlineWordId) {
                      //第三步
                      this.currentStep = 3
                      this.setThirdStep(res)
                      
                    }else if(1 == res.resultValue.checkStatus && res.resultValue.offlineWordId) {
                        //第四步，填写表单
                        this.currentStep = 4
                        this.setThirdStep(res)
                        this.form.subjectTitle = this.meetingName
                        this.form.recordFile = res.resultValue.recordFile || {}
                        this.form.notificationFile = res.resultValue.notificationFile || {}
                    }
                    $(".curtain").css("display", "none");
                  } else {
                      $(".curtain").css("display", "none");
                      mui.toast("请稍后再试", { duration: "long", type: "div" });
                  }
                },
                error: (e) => {
                    //失败回调
                    $(".curtain").css("display", "none");
                    mui.toast("请稍后再试", { duration: "long", type: "div" });
                },
            });
        },
        setThirdStep(res) {
            console.log(res.resultValue)
            this.voiceDuration = Number(res.resultValue.voiceDuration)
            this.audio_speaker_content = JSON.parse(res.resultValue.offlineVoiceContent)

            let downUrl = localUrlLink + iscp_port + '/tjAiAssistant/common/download';
            downUrl += '?id=' + res.resultValue.voiceAttach + '&userId=' + userId;
            let Authentication = sessionStorage.getItem("Authentication");
            let timestamp = new Date().getTime()+"";
            let sign = sm3(timestamp + '&' + res.resultValue.voiceAttach)
            downUrl += '&Authentication=' + Authentication + '&timestamp=' + timestamp + '&sign=' + sign;
            console.log('预览地址', downUrl)
            this.audioSrc = downUrl

            this.checkContentList = JSON.parse(res.resultValue.checkContent)
            this.errorList = JSON.parse(res.resultValue.checkResult)

            this.checkContentList.forEach(item => {
                if(item.replaceWord) {
                    item.word = item.replaceWord
                    this.errorList.forEach(errTypeList => {
                        errTypeList.data.forEach(errItem => {
                            if(item.word.indexOf('replaceWord' + errItem.id) >= 0) {
                                item.word = item.word.replace('replaceWord' + errItem.id, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                                // item.word = replaceCharAt(item.replaceWord, "replace"+item.id, item.start-item.start, item.end-item.start, "<span id='replace"+item.id+"' class='err-txt'>" + item.cont + "</span>")
                            }
                        })
                        })
                }
            })

            this.setSpeakerNameColor(this.checkContentList)

            this.errorList.forEach(item => {
                this.errorCount += item.count
            })
        },
        //查询语音转换结果
        queryTransResult(id) {
            const userId = sessionStorage.getItem("userId");
              let param = {
                "id": id,
                "timestamp": new Date().getTime() + ""
              };
              let AuthenticationSession = sessionStorage.getItem("Authentication");
              data = JSON.stringify(param)
              let sign = sm3(data);
              $.ajax({
                  url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/queryById",
                  type: "post",
                  async: false, //是否同步，false表示同步请求
                  dataType: "json",
                  data: data,
                  headers: {
                      "Content-Type": "application/json;charset=UTF-8",
                      Authentication: AuthenticationSession,
                      sign: sign
                  },
                  success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        this.transStatus = res.resultValue.transStatus
                      if(-1 == res.resultValue.transStatus) {
                        //等待中...
                        this.transingTip = "排队等待..."
                      }else if(0 == res.resultValue.transStatus) {
                        //转写中...
                        this.transingTip = "正在转写..."
                        this.recordTime = res.resultValue.recordTime
                      }else if(1 == res.resultValue.transStatus) {
                        $(".curtain").css("display", "none");
                        console.log(res.resultValue)
                        this.meetingId = id
                        // res.resultValue.voiceAttach = 3892
                        this.voiceDuration = Number(res.resultValue.voiceDuration)
                        this.audio_speaker_content = JSON.parse(res.resultValue.offlineVoiceContent)
                        
                        let downUrl = localUrlLink + iscp_port + '/tjAiAssistant/common/download';
                        downUrl += '?id=' + res.resultValue.voiceAttach + '&userId=' + userId;
                        let Authentication = sessionStorage.getItem("Authentication");
                        let timestamp = new Date().getTime()+"";
                        let sign = sm3(timestamp + '&' + res.resultValue.voiceAttach)
                        downUrl += '&Authentication=' + Authentication + '&timestamp=' + timestamp + '&sign=' + sign;
                        console.log('预览地址', downUrl)
                        this.audioSrc = downUrl
                        
                        this.setSpeakerNameColor(this.audio_speaker_content)
                        if(this.transTimer) {
                            clearInterval(this.transTimer)
                        }
                      }else if(2 == res.resultValue.transStatus) {
                        this.transErrCallBack()
                      }
                    } else {
                        this.transErrCallBack()
                        $(".curtain").css("display", "none");
                        // mui.toast("转写失败", { duration: "long", type: "div" });
                    }
                  },
                  error: (e) => {
                      //失败回调
                      this.transErrCallBack()
                      $(".curtain").css("display", "none");
                    //   mui.toast("转写失败", { duration: "long", type: "div" });
                  },
              });
        },
        loadOffline() {
            setTimeout(() => {
                this.$nextTick(() => {

                    let startTime = null;
                    let startScrollTop = 0;
                    const element = this.$refs['offlineScroll'];

                    element.addEventListener('scroll', () => {
                        if (startTime === null) {
                            startTime = new Date().getTime(); // 记录开始时间
                            startScrollTop = element.scrollTop; // 记录开始滚动位置
                        } else {
                            const currentTime = new Date().getTime();
                            const timeDiff = currentTime - startTime; // 时间差
                            const endScrollTop = element.scrollTop; // 当前滚动位置
                            const distanceScrolled = endScrollTop - startScrollTop; // 计算滚动距离
                            // console.log('distanceScrolled',distanceScrolled)
                            // 显示隐藏backTop图标
                            // console.log('endScrollTop', endScrollTop)
                            this.handleProcessClick.showBackTopIcon = Math.abs(this.handleProcessClick.scrollTop - endScrollTop) > 300 && this.handleProcessClick.isHandleProcess == true ? true : false

                            setTimeout(() => {
                                startTime = null; // 重置开始时间和滚动位置
                                // console.log(`滚动了 ${distanceScrolled} 像素`);
                                // 如果滚动的像素在此范围 就代表是用户在滑动滚动条
                                if (Math.abs(distanceScrolled) > 100) {
                                    this.handleProcessClick.isHandleProcess = true
                                }
                            }, 500)
                        }
                    });
                })
            }, 400)
        },
        //------文档校核------start
        //文档校核
        contentCheck() {
            // 文档校核后台请求
            $(".curtain").css("display", "block");
            let index = 0
            let tmpCheckContentList = []
            this.checkContentList = []
            this.audio_speaker_content.forEach(item => {
                let word = ''
                item.content.forEach((content, index2) => {
                    word = content.word
                    if(0 == index2) {
                        let checkSpeaker = {
                            "id": item.paragraphId + content.serialNum,
                            "speakerId": item.speakerId,
                            "showSpeakerName": true,
                            "speakerName": item.speakerName,
                            "speakerNameShow": item.speakerName + ":",
                            "word": word,
                            "originWord": word,
                            "start": index,
                            "end": index + word.length
                        }
                        tmpCheckContentList.push(checkSpeaker)
                    }
                    let checkContent = {
                        "id": item.paragraphId + content.serialNum + '_' + index2,
                        "speakerId": item.speakerId,
                        "showSpeakerName": false,
                        "speakerName": item.speakerName,
                        "speakerNameShow": item.speakerName + ":",
                        "word": word,
                        "originWord": word,
                        "start": index,
                        "end": index + word.length
                    }
                    tmpCheckContentList.push(checkContent)
                    index = checkContent.end + 1
                })
            })
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "id": this.meetingId,
                "meetingName": this.meetingName,
                "modelType": getLargeModelType(),
                "offlineVoiceContent": this.audio_speaker_content,
                //文档内容
                "contentList": tmpCheckContentList,
                "timestamp": new Date().getTime() + "",
            };
            this.errorCount = 0

        //     this.checkContentList = tmpCheckContentList
        //     this.errorList = [
        //         {
        //             "count": 9,
        //             "data": [
        //                 {
        //                     "cont": "标志标志着夏季达沃斯活动",
        //                     "end": 87,
        //                     "id": "55741ee7d9d44c00aa5f25d0637f70c0",
        //                     "rightCont": "标志着夏季达沃斯活动",
        //                     "start": 76
        //                 },
        //                 {
        //                     "cont": "100万瓦100万千瓦时电量",
        //                     "end": 201,
        //                     "id": "4ad655c616d7410e879d3034a90406b9",
        //                     "rightCont": "100万千瓦时电量",
        //                     "start": 188
        //                 },
        //                 {
        //                     "cont": "绿绿色电力消费意识",
        //                     "end": 320,
        //                     "id": "444091ef7d154b9889dcb6acca983f82",
        //                     "rightCont": "绿色电力消费意识",
        //                     "start": 312
        //                 },
        //                 {
        //                     "cont": "在主题展览中国网、天津电力聚焦能源转型、节能增效、低碳服务三方面，",
        //                     "end": 683,
        //                     "id": "e7388c2498214f8d9f51b6a35d3e705d",
        //                     "rightCont": "在主题展览中，国网天津电力聚焦能源转型、节能增效、低碳服务三方面，",
        //                     "start": 651
        //                 },
        //                 {
        //                     "cont": "雪豹网",
        //                     "end": 748,
        //                     "id": "19f2157bdaa74870a0b32fa633f00b4f",
        //                     "rightCont": "雪花网",
        //                     "start": 746
        //                 },
        //                 {
        //                     "cont": "目前已在中心天津生态城不动产登记中心实现实用化规模化落地应用。",
        //                     "end": 973,
        //                     "id": "50618447534249e191de56ab29b3351e",
        //                     "rightCont": "目前已在天津生态城不动产登记中心实现实用化规模化落地应用。",
        //                     "start": 943
        //                 },
        //                 {
        //                     "cont": "充换电量充换电次数在天津市公共充电站中均排第均排名第一，",
        //                     "end": 1081,
        //                     "id": "dcdac76ab13944059ee14a620c4597c5",
        //                     "rightCont": "充换电量和充换电次数在天津市公共充电站中均排名第一，",
        //                     "start": 1054
        //                 },
        //                 {
        //                     "cont": "我经常中午还在北京分公司吃工作餐，下午一上班便准时回到天津总公司开会，双重工作模式早已切换自如。",
        //                     "end": 1953,
        //                     "id": "b99038aef1fb49028be4ca52c5ee0512",
        //                     "rightCont": "我经常中午在北京分公司吃工作餐，下午准时回到天津总公司开会，这种双重工作模式早已切换自如。",
        //                     "start": 1906
        //                 },
        //                 {
        //                     "cont": "接治疗心脏病医生，告诉他该医院是全口径对接，河北省的医保定点医院，无需转诊证明可直接结算。",
        //                     "end": 2077,
        //                     "id": "ba1c973ba53941d7a864c44a846d4654",
        //                     "rightCont": "接诊的心脏病医生告诉他，该医院是全口径对接河北省的医保定点医院，无需转诊证明即可直接结算。",
        //                     "start": 2033
        //                 }
        //             ],
        //             "id": 3,
        //             "title": "语法错误",
        //             "type": 3
        //         },
        //         {
        //             "count": 8,
        //             "data": [
        //                 {
        //                     "cont": "二二氧化碳排放量",
        //                     "end": 375,
        //                     "id": "7830b8e570434d87a7c3bb6422133d23",
        //                     "rightCont": "二氧化碳排放量",
        //                     "start": 368
        //                 },
        //                 {
        //                     "cont": "绿电交易平台区块链技术",
        //                     "end": 533,
        //                     "id": "025c3a56cabb4777adcdf3aac494ebb7",
        //                     "rightCont": "绿电交易平台的区块链技术",
        //                     "start": 523
        //                 },
        //                 {
        //                     "cont": "首届上海国际碳中和技术产品与成果博览会",
        //                     "end": 586,
        //                     "id": "38cb54ca829f43f4acd937eebb42af28",
        //                     "rightCont": "首届上海国际碳中和技术、产品与成果博览会",
        //                     "start": 568
        //                 },
        //                 {
        //                     "cont": "0能耗小屋",
        //                     "end": 710,
        //                     "id": "ea576ce7a1a144449a7f32796ed90bb2",
        //                     "rightCont": "零能耗小屋",
        //                     "start": 706
        //                 },
        //                 {
        //                     "cont": "十佳国字号创新平台获批",
        //                     "end": 2236,
        //                     "id": "e2ac36d04c9044aebe59e66e9f6f418d",
        //                     "rightCont": "多个国家级创新平台获批",
        //                     "start": 2226
        //                 },
        //                 {
        //                     "cont": "中国新能源汽车第两千万辆线下线活动",
        //                     "end": 2485,
        //                     "id": "db178eb940f34da288789687e08e9e8e",
        //                     "rightCont": "中国新能源汽车第二千万辆下线活动",
        //                     "start": 2469
        //                 },
        //                 {
        //                     "cont": "从广汽泰安整车下线区",
        //                     "end": 2521,
        //                     "id": "7e72f066d66f4bfd9fa9287aac87c271",
        //                     "rightCont": "从广汽埃安整车下线区",
        //                     "start": 2512
        //                 },
        //                 {
        //                     "cont": "新能源汽车新车渗透率销售销量达到汽车新车总销量达达到27.7%",
        //                     "end": 2761,
        //                     "id": "b376253da1bb45868daccc500949749a",
        //                     "rightCont": "新能源汽车新车渗透率达到27.7%",
        //                     "start": 2731
        //                 }
        //             ],
        //             "id": 4,
        //             "title": "专业词语",
        //             "type": 4
        //         }
        //     ]

        // this.errorList.forEach(item => {
        //     this.errorCount += item.count
        // })
        // $(".curtain").css("display", "none");

       
        // console.log(param);
        // let AuthenticationSession = sessionStorage.getItem("Authentication");
        // let data = JSON.stringify(param)
        // let sign = sm3(data);
        // $.ajax({
        //       url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/checkContent",
        //       type: "post",
        //       async: false, //是否同步，false表示同步请求
        //       dataType: "json",
        //       data: data,
        //       headers: {
        //           "Content-Type": "application/json;charset=UTF-8",
        //           Authentication: AuthenticationSession,
        //           sign: sign
        //       },
        //       success: (res, txt, xhr) => {

        //         this.streaming = false
        //             $(".curtain").css("display", "none");
        //             //成功回调
        //             console.log(res)
        //             if(200 == res.code) {
        //                 let result = res.resultValue
                        
        //                 this.checkContentList = tmpCheckContentList
        //                 this.errorList = result.errorList
        //                 this.errorList.forEach(item => {
        //                     this.errorCount += item.count
        //                 })
        //             }else {
        //                 //请求异常
        //                 mui.toast("文档校核异常", { duration: "long", type: "div" });
        //                 this.streaming = false
        //             }
        //       },
        //       error: (e) => {
        //         this.streaming = false
        //         $(".curtain").css("display", "none");
        //         mui.toast("文档校核异常", { duration: "long", type: "div" });
        //       },
        //   });

          this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/checkContent", param,
            (res) => {
                this.streaming = true
                $(".curtain").css("display", "none");
                //成功回调
                console.log(res)
                if(200 == res.code) {
                    let result = res.resultValue
                    
                    this.checkContentList = tmpCheckContentList
                    this.errorList = result.errorList
                    this.errorList.forEach(item => {
                        this.errorCount += item.count
                    })
                }else {
                    //请求异常
                    mui.toast("文档校核异常", { duration: "long", type: "div" });
                    this.streaming = false
                }
            }, (err) => {
                //失败回调
                this.streaming = false
                $(".curtain").css("display", "none");
                mui.toast("文档校核异常", { duration: "long", type: "div" });
            }, (res) => {
                this.streaming = false
                $(".curtain").css("display", "none");
            });

            // this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/contentCheck", param,
            //     (res) => {
            //         this.streaming = true
            //         $(".curtain").css("display", "none");
            //         //成功回调
            //         console.log(res)
            //         if(200 == res.code) {
            //             let result = res.resultValue
                        
            //             this.checkContentList = tmpCheckContentList
            //             this.errorList = result.errorList
            //             this.errorList.forEach(item => {
            //                 this.errorCount += item.count
            //             })
            //         }else {
            //             //请求异常
            //             mui.toast("文档校核异常", { duration: "long", type: "div" });
            //             this.streaming = false
            //         }
            //     }, (err) => {
            //         //失败回调
            //         this.streaming = false
            //         $(".curtain").css("display", "none");
            //         mui.toast("文档校核异常", { duration: "long", type: "div" });
            //     }, (res) => {
            //         this.streaming = false
            //         $(".curtain").css("display", "none");
            //     });

        },
        setCheckContentList() {

            let index = 0
            let tmpCheckContentList = []
            this.checkContentList = []
            this.audio_speaker_content.forEach(item => {
                let word = ''
                item.content.forEach((content, index2) => {
                    word = content.word
                    if(0 == index2) {
                        let checkSpeaker = {
                            "id": item.paragraphId + content.serialNum,
                            "speakerId": item.speakerId,
                            "showSpeakerName": true,
                            "speakerName": item.speakerName,
                            "speakerNameShow": item.speakerName + ":",
                            "word": word,
                            "originWord": word,
                            "start": index,
                            "end": index + word.length
                        }
                        tmpCheckContentList.push(checkSpeaker)
                    }
                    let checkContent = {
                        "id": item.paragraphId + content.serialNum + '_' + index2,
                        "speakerId": item.speakerId,
                        "showSpeakerName": false,
                        "speakerName": item.speakerName,
                        "speakerNameShow": item.speakerName + ":",
                        "word": word,
                        "originWord": word,
                        "start": index,
                        "end": index + word.length
                    }
                    tmpCheckContentList.push(checkContent)
                    index = checkContent.end + 1
                })
            })

            this.checkContentList = tmpCheckContentList
        },
        handleCheckEdit() {
            if(this.errorList[0].count > 0) {
                mui.toast('请先更正完成再编辑', {
                    duration: 'long',
                    type: 'div'
                })
            }else {
                this.isCheckEditable = true
                mui.toast('点击文本进行编辑', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        //错误类型选择
        selErrorType(item){
            if(this.showErrDialog) {
                this.showErrDialog = false
                return
            }
            this.showErrDialog = false
            if(!item.data || 0 == item.data.length) {
                return
            }
            this.$nextTick(()=>{
                this.errorSel = item.type;
                // this.errTitle = item.title
                this.showErrDialog = true
                this.errContList = item.data
                //重新渲染成html

                let _errContList = this.errContList.slice().reverse()
                _errContList.forEach(errItem => {
                    // errItem['expand'] = false
                    this.$set(errItem, 'expand', false)
                    for(let i=0;i<this.checkContentList.length;i++) {
                        let checkItem = this.checkContentList[i]
                        if(checkItem.showSpeakerName) {
                            continue
                        }
                        if(!checkItem.replaceWord) {
                            checkItem.replaceWord = checkItem.word
                        }
                        //如果已错误已在页面上显示，这continue
                        if(checkItem.word.indexOf(errItem.id) >= 0) {
                            return false;
                        }
                        //如果是发言人错误
                        // if(checkItem.speakerNameShow.length >= errItem.end) {
                        //     checkItem.speakerNameShow = replaceCharAt(checkItem.speakerNameShow, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>", errItem.start-checkItem.start, errItem.end-checkItem.start, errItem.cont)
                        // }else 
                        if(checkItem.start <= errItem.start && checkItem.end >= errItem.end) {
                            checkItem.replaceWord = replaceCharAt(checkItem.replaceWord, "replaceWord"+errItem.id, errItem.start-checkItem.start, errItem.end-checkItem.start, errItem.cont)
                            checkItem.word = replaceCharAt(checkItem.word, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>", errItem.start-checkItem.start, errItem.end-checkItem.start, errItem.cont)
                            break;
                        }else if(errItem.start < checkItem.end && errItem.end > checkItem.end) {
                            //跨段落，判断在哪一个段落，当前是前面的段落
                            //前面的段落取最后errItem.cont.length + this.checkContentList.length 个字符，判断是否匹配
                            let length = errItem.cont.length + this.checkContentList.length
                            let _word = checkItem.word.substr(checkItem.word.length - length)
                            if(_word.indexOf(errItem.cont) >= 0) {
                                checkItem.replaceWord = replaceCharAt(checkItem.replaceWord, "replaceWord"+errItem.id, checkItem.word.length - length, checkItem.word.length, errItem.cont)
                                checkItem.word = replaceCharAt(checkItem.word, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>", checkItem.word.length - length, checkItem.word.length, errItem.cont)
                                break;
                            }else if(i < (this.checkContentList.length-1)){
                                //后面的段落取最前面的errItem.cont.length + this.checkContentList.length 个字符，判断是否匹配
                                let nextCheckItem = this.checkContentList[i+1]
                                let _word = nextCheckItem.word.substr(0, length)
                                if(_word.indexOf(errItem.cont) >= 0) {
                                    nextCheckItem.replaceWord = replaceCharAt(nextCheckItem.replaceWord, "replaceWord"+errItem.id, 0, length, errItem.cont)
                                    nextCheckItem.word = replaceCharAt(nextCheckItem.word, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>", 0, length, errItem.cont)
                                    break;
                                }
                            }
                        }
                    }
                })
            })
            
        },
        closeErrDialog(){
            this.showErrDialog = false
        },
        //定位到错误位置
        toErrorPos(item) {
            let element = document.getElementById('replace' + item.id)
            if (element) {
                element.scrollIntoView({ behavior: 'smooth', block: "center" });
                this.showPositionDialog = true
                // this.showErrDialog = false
                this.updateError = item
            }
            this.expandError(item)
        },
        //定位修改
        handleEditError(updateItem) {
            // 修改内容
            let errItem = updateItem || this.updateError
            for(let i=0;i<this.checkContentList.length;i++) {
                let checkItem = this.checkContentList[i]
                if(checkItem.showSpeakerName) {
                    continue
                }
                //如果是发言人错误
                // if(item.speakerNameShow.length >= error.end) {
                //     item.speakerNameShow = replaceCharAt(item.speakerName+":", error.rightCont, error.start-item.start, error.end-item.start, error.cont)
                //     if(item.speakerNameShow.indexOf(":") > 0) {
                //         item.speakerName = item.speakerNameShow.substr(0, item.speakerNameShow.indexOf(":"))
                //     }
                // }else 
                if(checkItem.start <= errItem.start && checkItem.end >= errItem.end) {
                    checkItem.word = replaceCharAt(checkItem.word, errItem.rightCont, checkItem.start, checkItem.end, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                    checkItem.replaceWord = replaceCharAt(checkItem.replaceWord, errItem.rightCont, checkItem.start, checkItem.end, "replaceWord"+errItem.id)
                    checkItem.originWord = replaceCharAt(checkItem.originWord, errItem.rightCont, errItem.start-checkItem.start, errItem.end-checkItem.start, errItem.cont)
                    break;
                }else if(errItem.start < checkItem.end && errItem.end > checkItem.end) {
                    //跨段落，判断在哪一个段落，当前是前面的段落
                    //前面的段落取最后errItem.cont.length + this.checkContentList.length 个字符，判断是否匹配
                    let length = errItem.cont.length + this.checkContentList.length
                    let _word = checkItem.originWord.substr(checkItem.originWord.length - length)
                    if(_word.indexOf(errItem.cont) >= 0) {
                        checkItem.word = replaceCharAt(checkItem.word, errItem.rightCont, 0, checkItem.word.length, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                        checkItem.replaceWord = replaceCharAt(checkItem.replaceWord, errItem.rightCont, 0, checkItem.word.length, "replaceWord"+errItem.id)
                        checkItem.originWord = replaceCharAt(checkItem.originWord, errItem.rightCont, checkItem.originWord.length - length, checkItem.originWord.length, errItem.cont)
                        break;
                    }else if(i < (this.checkContentList.length-1)){
                        //后面的段落取最前面的errItem.cont.length + this.checkContentList.length 个字符，判断是否匹配
                        let nextCheckItem = this.checkContentList[i+1]
                        let _word = nextCheckItem.originWord.substr(0, length)
                        if(_word.indexOf(errItem.cont) >= 0) {
                            nextCheckItem.word = replaceCharAt(nextCheckItem.word, errItem.rightCont, 0, nextCheckItem.word.length, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                            nextCheckItem.replaceWord = replaceCharAt(nextCheckItem.replaceWord, errItem.rightCont, 0, nextCheckItem.word.length, "replaceWord"+errItem.id)
                            nextCheckItem.originWord = replaceCharAt(nextCheckItem.originWord, errItem.rightCont, 0, length, errItem.cont)
                            break;
                        }
                    }
                }
            }
            this.removeCurrErr()
        },
        //定位忽略
        handleIgnoreError(updateItem) {

            let errItem = updateItem || this.updateError
            for(let i=0;i<this.checkContentList.length;i++) {
                let checkItem = this.checkContentList[i]
                if(checkItem.showSpeakerName) {
                    continue
                }
                if(checkItem.start <= errItem.start && checkItem.end >= errItem.end) {
                    checkItem.word = replaceCharAt(checkItem.word, errItem.cont, checkItem.start, checkItem.end, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                    checkItem.replaceWord = replaceCharAt(checkItem.replaceWord, errItem.cont, checkItem.start, checkItem.end, "replaceWord"+errItem.id)
                    break;
                }else if(errItem.start < checkItem.end && errItem.end > checkItem.end) {
                    //跨段落，判断在哪一个段落，当前是前面的段落
                    //前面的段落取最后errItem.cont.length + this.checkContentList.length 个字符，判断是否匹配
                    let length = errItem.cont.length + this.checkContentList.length
                    let _word = checkItem.originWord.substr(checkItem.originWord.length - length)
                    if(_word.indexOf(errItem.cont) >= 0) {
                        checkItem.word = replaceCharAt(checkItem.word, errItem.cont, 0, checkItem.word.length, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                        checkItem.replaceWord = replaceCharAt(checkItem.replaceWord, errItem.cont, 0, checkItem.word.length, "replaceWord"+errItem.id)
                        break;
                    }else if(i < (this.checkContentList.length-1)){
                        //后面的段落取最前面的errItem.cont.length + this.checkContentList.length 个字符，判断是否匹配
                        let nextCheckItem = this.checkContentList[i+1]
                        let _word = nextCheckItem.originWord.substr(0, length)
                        if(_word.indexOf(errItem.cont) >= 0) {
                            nextCheckItem.word = replaceCharAt(nextCheckItem.word, errItem.cont, 0, nextCheckItem.word.length, "<span id='replace"+errItem.id+"' class='err-txt'>" + errItem.cont + "</span>")
                            nextCheckItem.replaceWord = replaceCharAt(nextCheckItem.replaceWord, errItem.cont, 0, nextCheckItem.word.length, "replaceWord"+errItem.id)
                            break;
                        }
                    }
                }
            }

            this.removeCurrErr()
        },
        //删除当前错误
        removeCurrErr() {
            this.errContList = this.errContList.filter(item => item.id != this.updateError.id)
            this.errorList.forEach(item => {
                if(item.type == this.errorSel) {
                    item.data = item.data.filter(item => item.id != this.updateError.id)
                    item.count = item.data.length
                }
            })
            this.saveError()
            this.closePositionDialog()
        },
        saveError() {
            this.updateMeeting({
                'updateType': 2,
                "checkResult": this.errorList,
                "checkContent": this.checkContentList
            })
        },
        //关闭定位弹窗
        closePositionDialog(){
            this.showPositionDialog = false;
        },
        //一键忽略
        neglectAll(){
            this.showNDialog = true
        },
        //一键忽略确认
        nConfirm(){
            this.errorList.forEach(item => {
                item.data = []
                item.count = 0
            })
            this.errContList = []

            this.checkContentList.forEach(item => {
                item.word = item.originWord
            })

            this.showErrDialog = false
            this.saveError()
        },
        //一键忽略取消
        nCancle(){},
        //一键修正
        modifyAll(){
            this.showMDialog = true
        },
        //一键修正确认
        mConfirm(){
            // 错误列表集合
            let _errContList = []
            this.errorList.forEach(item => {
                _errContList = _errContList.concat(item.data)
            })
            //倒序
            _errContList.sort((a,b) => {
                return b.start - a.start
            })
            //替换
            _errContList.forEach(errItem => {
                for(let i=0;i<this.checkContentList.length;i++) {
                    let checkItem = this.checkContentList[i]
                    if(checkItem.showSpeakerName) {
                        continue
                    }
                    //如果是发言人错误
                    // if(item.speakerNameShow.length >= error.end) {
                    //     item.speakerNameShow = replaceCharAt(item.speakerName+":", error.rightCont, error.start-item.start, error.end-item.start, error.cont)
                    //     if(item.speakerNameShow.indexOf(":") > 0) {
                    //         item.speakerName = item.speakerNameShow.substr(0, item.speakerNameShow.indexOf(":"))
                    //     }
                    // }else 
                    if(checkItem.start <= errItem.start && checkItem.end >= errItem.end) {
                        checkItem.word = replaceCharAt(checkItem.originWord, errItem.rightCont, errItem.start-checkItem.start, errItem.end-checkItem.start, errItem.cont)
                        checkItem.originWord = checkItem.word
                        break;
                    }else if(errItem.start < checkItem.end && errItem.end > checkItem.end) {
                        //跨段落，判断在哪一个段落，当前是前面的段落
                        //前面的段落取最后errItem.cont.length + _errContList.length 个字符，判断是否匹配
                        let length = errItem.cont.length + _errContList.length
                        let _word = checkItem.originWord.substr(checkItem.originWord.length - length)
                        if(_word.indexOf(errItem.cont) >= 0) {
                            checkItem.word = replaceCharAt(checkItem.originWord, errItem.rightCont, checkItem.originWord.length - length, checkItem.originWord.length, errItem.cont)
                            checkItem.originWord = checkItem.word
                            break;
                        }else if(i < (this.checkContentList.length-1)){
                            //后面的段落取最前面的errItem.cont.length + _errContList.length 个字符，判断是否匹配
                            let nextCheckItem = this.checkContentList[i+1]
                            let _word = nextCheckItem.originWord.substr(0, length)
                            if(_word.indexOf(errItem.cont) >= 0) {
                                nextCheckItem.word = replaceCharAt(nextCheckItem.originWord, errItem.rightCont, 0, length, errItem.cont)
                                nextCheckItem.originWord = nextCheckItem.word
                                break;
                            }
                        }
                    }
                }
            })
            this.setSpeakerNameColor(this.checkContentList)
            this.errorList.forEach(item => {
                item.data = []
                item.count = 0
            })
            this.errContList = []

            this.showErrDialog = false
            this.saveError()
        },
        //一键更正取消
        mCancle(){

        },
        expandError(item) {
            this.$set(item, 'expand', !item.expand)
        },
        /**
         * 生成离线语音文档
         */
        createOfflineDoc() {
            userId = sessionStorage.getItem("userId");
            if (sessionStorage.getItem("iscp_port")) {
              iscp_port = sessionStorage.getItem("iscp_port");
            } else {
              iscp_port = ""
            }

            let newCheckContentList = []
            if(document.getElementById('checkContentHtml')) {
                this.checkContentList.forEach((item,index) => {
                
                    if(item.showSpeakerName) {
                        let _content = {...item}
                        newCheckContentList.push(_content)
                    }else {
                        let p_arr = document.querySelectorAll('[data-id="'+item.id+'"]');
                        let pIndex = 0
                        
                        p_arr.forEach((p, index2) => {
                            let _content = {...item}
                            _content.id = generateUUID()
                            _content.word = p.innerText
                            newCheckContentList.push(_content)
                            pIndex += 1
                        })
                    }
                })
                document.getElementById('checkContentHtml').innerHTML = ''
            }else {
                newCheckContentList = this.checkContentList
            }

            let param = {
                "userId": userId,
                "id": this.meetingId,
                "meetingName": this.meetingName,
                //文档内容
                "contentList": newCheckContentList,
                "timestamp": new Date().getTime() + "",
            };
            console.log("上传参数");
            console.log(param);
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                  url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/createOfflineDoc",
                  type: "post",
                  async: false, //是否同步，false表示同步请求
                  dataType: "json",
                  data: data,
                  headers: {
                      "Content-Type": "application/json;charset=UTF-8",
                      Authentication: AuthenticationSession,
                      sign: sign
                  },
                  success: (res, txt, xhr) => {
                        $(".curtain").css("display", "none");
                        if (res.code == 200) {
                            console.log(res.resultValue);

                            this.form.subjectTitle = res.resultValue.meetingName
                            this.form.recordFile = {
                               id: res.resultValue.offlineWordId,
                               fileName: res.resultValue.offlineFileName,
                               size: res.resultValue.offlineFileSize,
                               type: res.resultValue.offlineFileType,
                               img: "word",
                               fileSize: calcFileSize(res.resultValue.offlineFileSize)
                            }
                        }else {
                            //失败回调
                            mui.toast("会议记录文档生成失败", { duration: "long", type: "div" });
                        }
                  },
                  error: (e) => {
                      //失败回调
                      $(".curtain").css("display", "none");
                      mui.toast("会议记录文档生成失败", { duration: "long", type: "div" });
                  },
              });
        },
        //------文档校核------end

        //开始录音
        startTalk(type) {
            if(0 != this.voiceType) {
                mui.toast('正在录音.', {
                    duration: 'long',
                    type: 'div'
                })
            }else {
                this.voiceType = type
                this.voiceTxt = {
                    ind: '',
                    old: ''
                }
                if(1 == this.voiceType) {
                    this.checkClick = 1
                    this.voiceTxt.ind = this.realtimeVoiceContent
                }else if(2 == this.voiceType) {
                    this.voiceTxt.ind = this.form.highlight
                }else if(3 == this.voiceType) {
                    this.voiceTxt.ind = this.requireText
                }else if(4 == this.voiceType) {
                    this.voiceTxt.ind = this.form.subjectTitle
                }
                this.getMeToken()
            }
        },
        //停止录音
        stopTalk() {
            this.stopTalkCallBack()
            this.stopRecorder()
        },
        stopTalkCallBack() {
            var voiceInput = null;
            var voiceTextarea = null;
            var _text = '';
            if(1 == this.voiceType) {
                this.checkClick = 0
                _text = this.realtimeVoiceContent
                voiceTextarea = document.getElementById('realtimeVoiceContent')
            }else if(2 == this.voiceType) {
                _text = this.form.highlight
                voiceTextarea = document.getElementById('voiceHighlight')
            }else if(3 == this.voiceType) {
                _text = this.requireText
                voiceInput = document.getElementById('voiceRequireText')
            }else if(4 == this.voiceType) {
                _text = this.form.subjectTitle
                voiceInput = document.getElementById('voiceSubjectTitle')
            }

            this.$nextTick(() => {
                if(voiceInput) {
                    voiceInput.setSelectionRange(_text.length, _text.length)
                    voiceInput.scrollLeft = voiceInput.scrollWidth
                }
                if(voiceTextarea) {
                    voiceTextarea.setSelectionRange(_text.length, _text.length)
                    voiceTextarea.scrollTop = voiceTextarea.scrollHeight
                }
            })
            this.voiceType = 0
        },
        startTime() {
            console.log("开始进度条")
            this.time = setInterval(() => {
                this.voiceDuration += 1

                let hour = Math.floor(this.voiceDuration/3600) + ''
                let t_voice_duration = this.voiceDuration%3600
                let minute = Math.floor(t_voice_duration/60) + ''
                let second = t_voice_duration%60 + ''
                if(hour.length == 1) {
                    hour = '0' + hour
                }
                if(minute.length == 1) {
                    minute = '0' + minute
                }
                if(second.length == 1) {
                    second = '0' + second
                }
                this.one = hour
                this.two = minute
                this.three = second
            //   if (this.three === 59 || this.three === '59') {
            //     this.three = '00';
            //     this.abc = 0;
            //     if (this.two === 59 || this.two === '59') {
            //       this.two = '00';
            //       this.cde = 0;
            //       if (this.efg + 1 <= 9) {
            //         this.efg++;
            //         this.one = '0' + this.efg;
            //       } else {
            //         this.efg++;
            //         this.one = this.efg;
            //       }
            //     } else {
            //       if (this.cde + 1 <= 9) {
            //         this.cde++;
            //         this.two = '0' + this.cde;
            //       } else {
            //         this.cde++;
            //         this.two = this.cde;
            //       }
            //     }
            //   } else {
            //     if (this.abc + 1 <= 9) {
            //       this.abc++;
            //       this.three = '0' + this.abc;
            //     } else {
            //       this.abc++;
            //       this.three = this.abc;
            //     }
            //   }
            }, 1000)
          },
        getMeToken() {

            if(!this.meetingId) {
                this.createRealMeeting()
            }

            let _that = this
            var iscp_port = ''
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            }
            userId = sessionStorage.getItem("userId");
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let timestamp = new Date().getTime() + ""
            let data = {
                "userId": userId,
                "timestamp": timestamp,
            }
            const datas = JSON.stringify(data)
            let sign = sm3(datas);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/soundRecording/thirdparty",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: datas,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    sign: sign,
                    Authentication: AuthenticationSession,
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                                _that.WS_URL =
                                    `ws://127.0.0.1:${iscp_port}/websocket/asr/i?token=${res.resultValue}&capacityCode=${_that.CAPACITY_CODE}&language=${_that.LANG}&code=${_that.MODEL_CODE}&sessionId=${_that.VoiceItemID}`
                                if (!('WebSocket' in window)) {
                                    return
                                }
                                console.log("count:", _that.count)
                                if (_that.count < 1) {
                                    console.log("multiWindows_subscribe")
                                    wx.invoke("multiWindows_subscribe", { channelId: _that.wsChannelId }, function (res) {
                                        // console.log(res, "订阅返回结果")
                                        console.log(res.data.message, "信息")
                                        if (res.data.method == "onMessage String" && res.data.channelId == _that.wsChannelId) {
                                            _that.onMessage(res)
                                        } else if (res.data.method == 'onReconnectFinishAndDisconn') {
                                            //重连失败处理
                                            _that.stopVB()
                                        }
                                    });
                                }
                                _that.count++
                                wx.invoke("ext_AudioRecorder_Start", {
                                    data: {
                                        channelId: _that.wsChannelId,
                                        socketUrl: _that.WS_URL
                                    }
                                },
                                    function (res) {
                                        console.log("-----语音连接建立", res)
                                        if (res.err_msg === 'ext_AudioRecorder_Start:ok') {
                                            //成功处理
                                            console.log("-----语音连接建立成功")
                                            _that.checkClick = 1
                                            _that.startTime()
                                            _that.checkSwitch = true
                                            //初始化实时语音党建会议记录
                                            // _that.createRealMeeting()
                                        }

                                        if (res.err_msg === 'ext_AudioRecorder_Start:fail') {
                                            //失败处理
                                        }
                                        if (res.err_msg === 'ext_AudioRecorder_Start:cancel') {
                                            //取消处理
                                        }
                                        if (res.err_msg === 'ext_AudioRecorder_Start:not_support ') {
                                        }
                                    })
                            }
                        } else {
                            mui.toast(res.resultValue, {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    mui.toast('请求异常,请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            })
        },
        onOpen(evt, way, afterOpen) {
            let _that = this
            this.checkSwitch = true
            wx.startRecordVoiceBuffer({
                maxDuration: 100000000,
                sampleRate: 16000
            });
            wx.onRecordBufferReceived(function (res) {
                if (_that.isflageIOX) {
                    var a = ''
                    if (_that.bufferData.length == 26) {
                        _that.bufferData.forEach((item) => {
                            a += item
                            _that.bufferData = []
                        })
                        _that.doSend(a);
                    } else {
                        _that.bufferData.push(res.buffer)
                    }
                } else {

                    _that.doSend(res.buffer);
                }
            })
            this.startTime()
            if (!$(this).hasClass("stop")) {
                $(this).addClass("stop");
                let i = 0;
                $(this).data("interval", window.setInterval(function () {
                    $(".record-time").html((++i) + "s");
                }, 1000, i));
            }
        },
        doSend(message) {
            this.myWebsocket.readyState === 1 && this.myWebsocket.send(message);
        },
        onMessage(evt) {
            try {
                // const data = JSON.parse(evt.data);
                const data = JSON.parse(evt.data.message);
                console.log(evt.data,"内容")
                if (data.code == 200) {
                    // 这一行是赋值的
                    data.word = data.word.replace(/[|]/g, '\n')
                    data.word = data.word.replace(/[\n]/g, '\n\n')
                    this.insertContent(data)
                } else if (data.code == 'E000004') {
                    mui.toast("当前已达到最大并发量限制,请稍后再试", {
                        duration: 'long',
                        type: 'div'
                    })
                    this.stopRecorder()
                } else {
                    mui.toast(data.code + "语音服务异常", {
                        duration: 'long',
                        type: 'div'
                    })
                    this.stopRecorder()
                }
            } catch (error) {
                throw new Error('解析错误!' + error);
            }
        },
        insertContent(data) {
            let txt = data.word
            let ctxt = ''

            // if(this.voiceContentTmp.indexOf(data.serialNum+data.word+data.completed) >= 0) {
            //     console.log("重复数据", his.voiceContentTmp.indexOf(data.serialNum+data.word+data.completed))
            //     await new Promise(r => setTimeout(r, 100));
            //     return
            // }
            // this.voiceContentTmp.push(data.serialNum+data.word+data.completed)

            if(data.completed)  {
                console.log("返回completed的语音内容", data)
                //完成
                this.voiceTxt.old += txt
                ctxt = this.voiceTxt.old
            }else {
                //未完成
                ctxt = this.voiceTxt.old + txt
            }
            var voiceInput = null;
            var voiceTextarea = null;
            var _text = this.voiceTxt.ind + ctxt;
            if(1 == this.voiceType) {
                this.realtimeVoiceContent = this.voiceTxt.ind + ctxt
                voiceTextarea = document.getElementById('realtimeVoiceContent')
                if(data.completed) {
                    //实时语音转写结果保存
                    this.updateMeeting({
                        'updateType': 1,
                        "voiceDuration": this.voiceDuration,
                        "realtimeSessionId": this.VoiceItemID,
                        "realtimeVoiceContent": this.realtimeVoiceContent
                    })
                }
            }else if(4 == this.voiceType) {
                this.form.subjectTitle = this.voiceTxt.ind + ctxt
                voiceInput = document.getElementById('voiceSubjectTitle')
            }else if(2 == this.voiceType) {
                this.form.highlight = this.voiceTxt.ind + ctxt
                voiceInput = document.getElementById('voiceHighlight')
            }else if(3 == this.voiceType) {
                this.requireText = this.voiceTxt.ind + ctxt
                voiceInput = document.getElementById('voiceRequireText')
            }

            this.$nextTick(() => {
                if(voiceInput) {
                    voiceInput.setSelectionRange(_text.length-1, _text.length)
                    voiceInput.focus()
                    voiceInput.scrollLeft = voiceInput.scrollWidth
                }
                if(voiceTextarea) {
                    voiceTextarea.setSelectionRange(_text.length-1, _text.length)
                    voiceTextarea.focus()
                    voiceTextarea.scrollTop = voiceTextarea.scrollHeight
                }
            })
        },
        stopRecorder(num) {
            let _this = this
            wx.invoke("ext_AudioRecorder_Stop", {
                data: {}
            },
                function (res) {
                    console.log("停止录音", res)
                    if (res.err_msg === 'ext_AudioRecorder_Stop:ok') {
                        _this.stopVB(num)
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:fail') {
                        //失败处理
                        console.log(res);
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:cancel') {
                        //取消处理
                        console.log(res);
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:not_support ') {
                        _this.stopVB(num)
                        wx.stopRecordVoiceBuffer({});
                        // if (_this.myWebsocket) {
                        _this.myWebsocket.close();
                    }
                })
        },
        stopVB(num) {
            //成功处理
            this.time = clearInterval(this.time)
            // this.flag = true
            this.checkSwitch = false
            this.checkClick = 0
            $(this).removeClass("stop");
            window.clearInterval($(this).data("interval"));
            $(".record-time").html("");
        },

        // 上传文件---start
        uploadFunc(type) {
            if(1 == type && !this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
                return
            }
            this.fileType = type
            let _that = this
            wx.invoke("ext_FileBrowser_StartPreView", {}, function (res) {
                _that.channelId = "meeting_upload_" + createNonceStr(8) + new Date().getTime() + "";

                _that.progress = 0
                wx.invoke("multiWindows_subscribe", {
                    channelId: _that.channelId
                }, function (res) {
                    console.log("进度条", res)
                    if (res.err_msg == "multiWindows_subscribe:ok") {
                        var progress = Number(res.data.progress) >= 100 ? 99 : Number(res.data.progress)
                        _that.progress = progress > _that.progress ? progress : _that.progress
                    }
                })

                if (_that.isflageIOX) {
                    const suffix = res.name.split('.').reverse()[0]
                    if(0 == type) {
                        if (!_that.pdfAndImgSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择PDF或图片', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                    }else if(3 == type) {
                        //语音文件
                        if (!_that.voiceSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择wav,mp3,m4a,amr音频文件', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                    }else if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase())) {
                        mui.toast('请选择WORD文档', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    if (checkFileNameForSensitiveWords(res.name)) {
                        mui.toast('检测到敏感内容，请确认后再试。', {
                            duration: 'long',
                            type: 'div'
                        })
                        return false
                    }
                    _that.checkList(res.filePath, res.name, _that.channelId, res.size)
                } else {
                    let recordArr = JSON.parse(res.result)
                    const suffix = recordArr[0].name.split('.').reverse()[0]
                    if(0 == type) {
                        if (!_that.pdfAndImgSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择PDF或图片', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                    }else if(3 == type) {
                        //语音文件
                        if (!_that.voiceSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择wav,mp3,m4a,amr音频文件', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                    }else if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase())) {
                        mui.toast('请选择WORD文档', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    if (checkFileNameForSensitiveWords(recordArr[0].name)) {
                        mui.toast('检测到敏感内容，请确认后再试。', {
                            duration: 'long',
                            type: 'div'
                        })
                        return false
                    }
                    _that.checkList(recordArr[0].path, recordArr[0].name, _that.channelId, recordArr[0].fileSize)
                }
            })
        },
        checkList(path, name, id, fileSize, hash, index) {
            // $(".curtain").css("display", "block");
            let that = this
            that.disabledInp = true
            that.progressBar = true
            that.isformClassActive = true;
            let iscp_port
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = ""
            }
            let Authentication = sessionStorage.getItem("Authentication");
            const timestamp = new Date().getTime() + ""
            let userId = sessionStorage.getItem("userId");
            let sign = sm3(timestamp + "&" + userId)
            that.fileName = name
            wx.invoke("ext_Net_FragmentUpload", {
                data: {
                    serverAddress: localUrlLink + iscp_port + `/tjAiAssistant/storage/splitUpload2?channelId=${id}`,
                    filePath: path,
                    fragmentSize: that.CHUNK_SIZE,
                    fileName: name,
                    fileHash: hash ? hash : '',
                    upLoadFragmentIndex: index ? index : '',
                    channelId: id,
                    headerData: {
                        sign: sign,
                        userId: userId,
                        type: '',
                        timestamp: timestamp,
                        Authentication: Authentication,
                    }
                },
            }, function (res) {
                console.log("文件上传结果", res)
                if (res.err_msg.endsWith(":ok")) { //成功结果
                    //上传完成
                    // that.recording(id)
                    that.progress = 100
                    that.isfinish = true;
                    addPendingData(111, id)
                    if(that.fileType == 3 && that.meetingType == 1) {
                        that.nextStep()
                    }else if(that.fileType != 3) {
                        that.uploadComplete(id, name, fileSize)
                    }
                } else if (res.err_msg.endsWith(":cancel")) {
                    that.cleanData();
                    return
                } else {
                    //上传失败
                    if (that.myindex != Number(res.upLoadFragmentIndex)) {
                        that.myindex = Number(res.upLoadFragmentIndex);
                        that.retryNum = 0;
                    }
                    setTimeout(() => {
                        if (that.retryNum > 4) {
                            $(".curtain").css("display", "none");
                            // that.retryNum = 0
                            var btnArray = ["取消", "确定"];
                            var i = 0
                            mui.confirm(
                                "是否进行重试？",
                                "上传失败",
                                btnArray,
                                (e) => {
                                    if (i > 0) return
                                    i++
                                    if (e.index == 1) {
                                        that.checkList(path, name, id, fileSize, res.fileHash, res.upLoadFragmentIndex)
                                    } else {
                                        that.isformClassActive = false;
                                        that.cleanData()
                                    }
                                }
                            );
                        } else {
                            that.retryNum++

                            that.checkList(path, name, id, fileSize, res.fileHash, res.upLoadFragmentIndex)
                        }

                    }, (that.retryNum + 1) * 1000)

                }
            })
        },
        calcFileSize(fileSize) {
            let kbf = (Math.floor((fileSize / 1024) * 100) / 100).toFixed(2);
            if (kbf > 1000) {
                //显示 MB
                return (Math.floor((fileSize / (1024 * 1024)) * 100) / 100).toFixed(2) + 'MB';
            }
            return kbf + 'KB';
        },
        cleanData() {
            this.fileType = -1
            this.disabledInp = false
            this.progressBar = false
        },
        uploadComplete(id, name, fileSize) {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "channelId": id,
                "type": 5,
                "modelType": "BAIDU", //getLargeModelType(),
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/writing/word2Md",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    $(".curtain").css("display", "none");
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            let attach = res.resultValue
                            if (0 == this.fileType) {
                                let suffix = name.split('.').reverse()[0]

                                let img = "img"
                                if(this.pdfSuffix.includes(suffix.toLocaleLowerCase())) {
                                    img = "pdf"
                                }else if(this.imgSuffix.includes(suffix.toLocaleLowerCase())) {
                                    img = "img"
                                }

                                this.form.notificationFile = {
                                    id: attach.channelId,
                                    fileName: name,
                                    type: img.toUpperCase(),
                                    img: img,
                                    size: fileSize,
                                    fileSize: calcFileSize(fileSize)
                                }
                            } else if (1 == this.fileType) {
                                this.improveFile = {
                                    id: attach.channelId,
                                    fileName: name,
                                    type: 'WORD',
                                    img: "word",
                                    size: fileSize,
                                    fileSize: calcFileSize(fileSize)
                                }
                            } else if (2 == this.fileType) {
                                this.form.recordFile = {
                                    id: attach.channelId,
                                    fileName: name,
                                    type: 'WORD',
                                    img: "word",
                                    size: fileSize,
                                    fileSize: calcFileSize(fileSize)
                                }
                            }
                        } else {
                            let msg = res.resultValue
                            if('文件不能为空' != msg) {
                                msg = "请稍后再试"
                            }
                            mui.toast(msg, {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                    this.fileType = -1
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    this.fileType = -1
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        // 上传文件---end

        // 生成内容--编辑--start
        handleResize(){
            this.$nextTick(()=>{
                var originalHeight=document.documentElement.clientHeight ||document.body.clientHeight;
                window.onresize = () => {
                    var resizeHeight=document.documentElement.clientHeight || document.body.clientHeight;
                    if(resizeHeight<originalHeight){
                        this.bottomShow = false
                    } else {
                        this.bottomShow = true
                    }
                }
            })
        },
        handleInputFocus() {
            if(!this.voiceType) {
                this.bottomShow = false
            }
        },
        handleInputBlur() {
            this.bottomShow = true
        },
        delFile(type) {
            if(0 == type) {
                this.form.notificationFile = {}
            }else if(1 == type) {
                this.improveFile = {}
            }else if(2 == type) {
                // this.$set(this.form, 'recordFile', {})
                this.form.recordFile = {}
            }
            this.fileType = -1
        },
        // 生成内容--编辑--end

        // 生成内容--流式结果--start
        markdown2Html(tmd) {
            let md = tmd.replace(/\`\`\`markdown/g, '').replace(/\`\`\`/g, '').replace(/\\n/g, "\n").replace(/\n/g, "  \n\n")
            
            try{
                md = decodeURIComponent(md)
            }catch (error) {
                md = md
            }
            return marked.parse(md)
        },
        validForm() {
            if(!this.form.subjectTitle) {
                mui.toast("请填写标题", { duration: "long", type: "div" });
                return false
            }
            if(!this.form.recordFile.id) {
                mui.toast("请上传会议记录", { duration: "long", type: "div" });
                return false
            }
            return true
        },
        genContent(param) {
            if(!this.validForm()) {
                $(".curtain").css("display", "none");
                return
            }
            // 生成内容后台请求
            const userId = sessionStorage.getItem("userId");
            
            param = {
                "id": this.meetingId,
                "userId": userId,
                "subjectTitle": this.form.subjectTitle,
                "materialList": this.form.recordFile.id,
                "highlight": this.form.highlight,
                "modelType": 'DeepSeekR1', //getLargeModelType(),
                "type": 5, //会议纪要
                "timestamp": new Date().getTime() + "",
            };
            if(this.form.notificationFile.id) {
                param['notification'] = this.form.notificationFile.id
            }
            
            $(".curtain").css("display", "block");
            
            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/genContent", param,
                (res) => {
                    //成功回调
                    this.streaming = true
                    console.log(res)
                    $(".curtain").css("display", "none");
                    if(200 == res.code) {
                        let result = res.resultValue
                        this.infSessionId = result.sessionId
                        
                        this.programMdContent += result.content
                        // 将Markdown转换为HTML
                        this.programHtmlContent = this.markdown2Html(this.programMdContent)
                        this.handleScrollBottom('contentRef')

                        if(result.end) {
                            this.replaceContent = ''
                        }
                    }else {
                        //请求异常
                        this.streaming = false
                        mui.toast("生成内容异常", { duration: "long", type: "div" });
                    }
                }, (err) => {
                    //失败回调
                    this.streaming = false
                    $(".curtain").css("display", "none");
                    mui.toast("生成内容异常", { duration: "long", type: "div" });
                }, res => {
                    debugger
                    this.streaming = false
                    this.addClickEvent()
                    mui.toast("生成内容完成", { duration: "long", type: "div" });
                    $(".curtain").css("display", "none");
                });
        },
        handleImproveTalk() {
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
                return
            }
            this.startTalk(3)
        },
        //编辑流式内容
        handleEditPContent(){
            let pEle = document.getElementById(this.curPId)
            phtml = pEle.innerHTML
            // pEle.classList.remove('p-edit')
            this.showEditDialog = true
            this.editGenCont = phtml
            this.tempEditGenCont = phtml
        },
        //编辑取消
        editCancle(){
            this.editGenCont = ''
            this.showEditDialog = false
        },
        //修改内容
        changeCont(event){
            this.tempEditGenCont = event.target.innerHTML;
        },
        //编辑确认
        editConfirm(){
            let pEle = document.getElementById(this.curPId)
            pEle.innerHTML = this.tempEditGenCont
            let _editGenCont = this.tempEditGenCont.replace(/\<br\>/g,'')
            if(!_editGenCont) {
                console.log('this.tempEditGenCont', this.tempEditGenCont)
                pEle.remove()
            }
            this.programHtmlContent = document.getElementById('step5-mdBody').innerHTML
            this.programMdContent = html2Md(this.programHtmlContent)
           
            this.addClickEvent()
            
            this.showEditDialog = false
        },
        //选中续写等
        selQuickType(event, item) {
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
            }else if(this.quickSel == item.type){
                this.quickSel = ''
                this.writeTitle = ''
            }else {
                this.quickSel = item.type
                // this.showExConPo = true
                this.writeTitle = item.title
            }
            event.preventDefault()
        },
        //停止生成
        stopGen(){
            this.generating = false;
            this.abortCtrl.abort()
        },
        //重写
        reGen() {
            this.genImprove()  
        },
        //取消替换
        contentCancle(){
            this.replaceHtmlContent = ''
            this.showExConPo = false;
        },
        //替换
        contentReplace() {
            let pEle = document.getElementById(this.curPId)
            if('p' == pEle.nodeName.toLocaleLowerCase()) {
                pEle.classList.remove('p-edit')
                let firstTagHtml = getFirstHtmlTag(this.replaceHtmlContent)
                firstTagHtml = firstTagHtml.substring(0, firstTagHtml.length-1)
                let addHtml = ' class="p-edit" id="' + this.curPId + '"'
                let endHtml = this.replaceHtmlContent.substring(firstTagHtml.length)
                let newHtml = firstTagHtml + addHtml + endHtml
                pEle.outerHTML = newHtml
            }else {
                pEle.innerHTML = this.replaceHtmlContent
            }

            this.programHtmlContent = document.getElementById('step5-mdBody').innerHTML
            this.programMdContent = html2Md(this.programHtmlContent)

            this.addClickEvent()

            this.curPId = ''
            this.quickSel = ''
            this.showExConPo = false
        },
        //生成内容重新、扩写、续写、润色
        genImprove() {
            this.stopTalk()
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
                return
            }
            if(!this.quickSel) {
                mui.toast("请先选择扩写、续写或润色", { duration: "long", type: "div" });
                return
            }
            this.replaceContent = ''
            this.replaceHtmlContent = ''
            this.generating = true
            this.showExConPo = true
            $(".curtain").css("display", "block");
            //TODO 扩写、续写、润色后台请求
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": this.meetingId,
                "userId": userId,
                "type": 5, //党建会议助手
                 //扩写、续写、润色
                "improveType": this.quickSel,
                //选择的内容--待优化的内容
                "improveContent": document.getElementById(this.curPId).innerText,
                //待优化的要求，文本框输入的
                "improveNeed": this.requireText,
                //上传的文件
                "improveFile": this.improveFile.id,
                "modelType": getLargeModelType(),
                "timestamp": new Date().getTime() + "",
            };

            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/genImprove", param,
                (res) => {
                    this.streaming = true
                    $(".curtain").css("display", "none");
                    this.requireText = ''
                    //成功回调
                    console.log(res)
                    if(200 == res.code) {
                        let result = res.resultValue

                        // 将Markdown转换为HTML
                        this.replaceContent += result.content
                        this.replaceHtmlContent = this.markdown2Html(this.replaceContent)
                        this.handleScrollBottom('improveRef')
                    }else {
                        //请求异常
                        this.streaming = false
                        let msg = "expand"==this.quickSel ? "扩写" : ("continued"==this.quickSel ? "续写" : "润色")
                        mui.toast(msg + "异常", { duration: "long", type: "div" });
                    }
                }, (err) => {
                    //失败回调
                    this.streaming = false
                    $(".curtain").css("display", "none");
                    let msg = "expand"==this.quickSel ? "扩写" : ("continued"==this.quickSel ? "续写" : "润色")
                    mui.toast(msg + "异常", { duration: "long", type: "div" });
                }, e => {
                    //请求完成
                    this.streaming = false
                    $(".curtain").css("display", "none");
                    this.generating = false
                });
        },
        addPopoverClick() {
            window.addEventListener('click', (event) => {
                event.preventDefault()
                let myPopover = document.getElementById('myPopover')
                if(myPopover) {
                    myPopover.style.display = 'none'
                }
            })
        },
        //添加点击事件
        addClickEvent(){
            setTimeout(()=>{
                this.$nextTick(() => {
                    // 获取div元素
                    var div = document.getElementById('step5-mdBody');
                    
                    this.addElementList.forEach((em) => {
                        // 获取div内的所有元素
                        var pItems = div.querySelectorAll(em);

                        // 添加事件监听器
                        pItems.forEach((pElement) => {
                            pElement.addEventListener('click', (event) => {

                                //再次点击，取消编辑
                                if(this.curPId && pElement.id == this.curPId) {
                                    var clsItems = document.querySelectorAll(".p-edit");
                                    if(clsItems){
                                        clsItems.forEach((cItem) => {
                                            cItem.classList.remove('p-edit')
                                        })
                                    }
                                    // popover元素
                                    var popover = document.getElementById('myPopover');
                                    if(popover) {
                                        popover.style.display = 'none';
                                    }
                                    this.curPId = ''
                                }else {
                                    event.preventDefault()
                                    var clsItems = document.querySelectorAll(".p-edit");
                                    if(clsItems){
                                        clsItems.forEach((cItem) => {
                                            cItem.classList.remove('p-edit')
                                        })
                                    }
                                    
                                    pElement.classList.add("p-edit"); // 增加class
                                    if(!pElement.id) {
                                        pElement.id = 'md-'+em+'-' + new Date().getTime();
                                    }
    
                                    this.$nextTick(() => {
                                        this.curPId = pElement.id
    
                                        // popover元素
                                        var popover = document.getElementById('myPopover');
                                        // 设置popover的位置
                                        let scrollElem = this.$refs['contentRef'];
                                        
                                        let header = document.getElementsByClassName('header_tit')[0]
    
                                        let autoHeight = 10
                                        if('block' == popover.style.display) {
                                            autoHeight = 40
                                        }
        
                                        popover.style.top = (pElement.offsetTop - header.offsetHeight - autoHeight) + 'px';
                                        popover.style.left = pElement.offsetLeft + pElement.offsetWidth/2 - 30 + 'px';
                                        
                                        popover.style.scrollTop = scrollElem.scrollTop
                                        
                                        // 显示popover
                                        popover.style.display = 'block';
        
                                        // 添加关闭popover的事件监听
                                        popover.addEventListener('click', function() {
                                            popover.style.display = 'none';
                                        });
                                    })
                                }

                                event.stopPropagation()
                            });
                        });
                    })
                });
            },500)
            
        },
        // 生成内容--流式结果--end

        //生成文档
        createDoc() {
            setTimeout(() => {
                
                const userId = sessionStorage.getItem("userId");
                let param = {
                    "id": this.meetingId,
                    "userId": userId,
                    "subjectTitle": this.form.subjectTitle,
                    "offlineWordId": this.form.recordFile.id,
                    "type": 5,
                    "modelType": getLargeModelType(),
                    //文档内容
                    "content": html2Md(this.programHtmlContent),
                    "timestamp": new Date().getTime() + "",
                };
                let AuthenticationSession = sessionStorage.getItem("Authentication");
                data = JSON.stringify(param)
                let sign = sm3(data);
                $.ajax({
                    url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/createDoc",
                    type: "post",
                    async: false, //是否同步，false表示同步请求
                    dataType: "json",
                    data: data,
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        Authentication: AuthenticationSession,
                        sign: sign
                    },
                    success: (res, txt, xhr) => {
                        if (res.code == 200) {
                            let data = res.resultValue
                            let word = data.word
                            let _offlineWord = data.offlineWord
                            let voiceAttach = data.voiceAttach
                            this.$set(this.wordResult, 'id', word.id)
                            this.wordResult['fileName'] = word.name
                            this.wordResult['type'] = 'word'
                            this.wordResult['size'] = word.size
                            this.wordResult['fileSize'] = calcFileSize(word.size)

                            this.$set(this.offlineWord, 'id', _offlineWord.id)
                            this.offlineWord['fileName'] = _offlineWord.name
                            this.offlineWord['type'] = 'word'
                            this.offlineWord['size'] = _offlineWord.size
                            this.offlineWord['fileSize'] = calcFileSize(_offlineWord.size)

                            this.$set(this.voiceAttach, 'id', voiceAttach.id)
                            let voiceAttachName = voiceAttach.name.substring(0, voiceAttach.name.indexOf("."))
                            this.voiceAttach['fileName'] = voiceAttachName + '录音文件' + voiceAttach.suffix
                            this.voiceAttach['type'] = voiceAttach.suffix.substr(1).toUpperCase()
                            this.voiceAttach['size'] = voiceAttach.size
                            this.voiceAttach['fileSize'] = calcFileSize(voiceAttach.size)
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    },
                    error: (e) => {
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    },
                });
            }, 1000);
        },
        createDoc2() {
            userId = sessionStorage.getItem("userId");
            if (sessionStorage.getItem("iscp_port")) {
              iscp_port = sessionStorage.getItem("iscp_port");
            } else {
              iscp_port = ""
            }
            let param = {
                "userId": userId,
                "id": this.meetingId,
                "meetingName": this.meetingName,
                //文档内容
                "contentList": this.checkContentList,
                "timestamp": new Date().getTime() + "",
            };
            console.log("上传参数");
            console.log(param);
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                  url: localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/createDoc2",
                  type: "post",
                  async: false, //是否同步，false表示同步请求
                  dataType: "json",
                  data: data,
                  headers: {
                      "Content-Type": "application/json;charset=UTF-8",
                      Authentication: AuthenticationSession,
                      sign: sign
                  },
                  success: (res, txt, xhr) => {
                        $(".curtain").css("display", "none");
                        if (res.code == 200) {
                            let data = res.resultValue
                            let word = data.word
                            let _offlineWord = data.offlineWord
                            this.$set(this.wordResult, 'id', word.id)
                            this.wordResult['fileName'] = word.name
                            this.wordResult['type'] = 'word'
                            this.wordResult['size'] = word.size
                            this.wordResult['fileSize'] = calcFileSize(word.size)

                            this.$set(this.offlineWord, 'id', _offlineWord.id)
                            let offlineWordName = word.name.substring(0, word.name.indexOf("."))
                            this.offlineWord['fileName'] = offlineWordName + '录音文件' + _offlineWord.suffix
                            this.offlineWord['type'] = _offlineWord.suffix.substr(1).toUpperCase()
                            this.offlineWord['size'] = _offlineWord.size
                            this.offlineWord['fileSize'] = calcFileSize(_offlineWord.size)
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                  },
                  error: (e) => {
                      //失败回调
                      $(".curtain").css("display", "none");
                      mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                  },
              });
        },
        //创建pdf
        createPdf(item) {
            if(!item.id) {
                return
            }
            if(this.pptResult.id) {
                return
            }
            // $(".curtain").css("display", "block");
            this.pptLoading = true
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": this.meetingId,
                "wordId": this.wordResult.id ? this.wordResult.id : "",
                "userId": userId,
                "type": 5,
                "modelType": getLargeModelType(),
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);

            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/meetingFour/createPdf", param,
                (res) => {
                    //成功回调
                    // console.log(res)
                    $(".curtain").css("display", "none");
                    if (res.code == 200) {
                        this.pptResult = {
                            "id": res.resultValue.id,
                            "fileName": res.resultValue.name,
                            "type": 'pdf',
                            "size": res.resultValue.size,
                            "fileSize": calcFileSize(res.resultValue.size),
                        }
                        mui.toast("PDF生成完成", { duration: "long", type: "div" });
                    } else {
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    }
                }, (err) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                }, res => {
                    $(".curtain").css("display", "none");
                });
        },

        handleScrollBottom(refName) {
            // this.$nextTick(() => {
                let scrollElem = this.$refs[refName];
                if(scrollElem) {
                    $(scrollElem).stop(true, true)
                    $(scrollElem).animate({ scrollTop: $(scrollElem).prop('scrollHeight')},20)
                }
            // })
        },
        preview(item) {
            myPreviewFile(item)
        },
        //分享
        shareIgw(item) {
            if(!item.id) {
                return
            }
            shareIgw({
                sceneNo: '111',
                shareType: 1,
                attchId: item.id
            })
         },
        //文件发送邮箱
        sendMyEmail(result) { 
            if(!result.id) {
                return
            }
            mySendMail('党建会议', "answerAttach="+result.id, 11, 1)
        },
        // 判断安卓还是ios
        compatibleInput() {
            //获取浏览器的userAgent,并转化为小写
            var ua = navigator.userAgent.toLowerCase();
            //判断是否是苹果手机，是则是true
            var isIos = ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1;
            if (isIos) {
                this.isflageIOX = true;
            } else {
                this.isflageIOX = false;
            }
        },
        home() {
            this.stopTalk()
            $(location).attr("href", "index.html");
        },
        createSgin(data) {
            let hashData = sm3(data);
            let hashData_last = sm3(hashData);
            hashData_last = hashData_last.substr(0, 5);
            hashData += hashData_last;
            let sign = hashData;
            return sign;
        },
    }
})